pazta
pazta

Reputation: 371

moment unix timestamp formats wrong date

I want to convert an Unix milliseconds timestamp to readable date.

My timestamp is 1525772511140. The correct output should be something like: 29-05-2018 9:41:51AM

Now my code returns a wrong date: 31-10-50319 03:10...

code:

var timeStamp = new Date(1525772511140 * 1000);
var date = moment(timeStamp).format('DD-MM-YYYY HH:mm');
console.log(date);

Upvotes: 4

Views: 10567

Answers (6)

noobmaster007
noobmaster007

Reputation: 163

I had the same problem where I was getting the unix timestamp in milliseconds. What worked for me was dividing the unix timestamp by 1000 and use with moment.unix() since moment.unix takes timestamp value in seconds:

let formattedDate = moment.unix(1646394914141 / 1000).format("yyyy-MM-DD hh:mm:ss");
console.log(formattedDate); // 2022-03-04 03:13:56

Upvotes: 0

VincenzoC
VincenzoC

Reputation: 31482

You can simply use moment(Number):

Similar to new Date(Number), you can create a moment by passing an integer value representing the number of milliseconds since the Unix Epoch (Jan 1 1970 12AM UTC)

var date = moment(1525772511140).format('DD-MM-YYYY HH:mm');
console.log(date);
// with seconds and AM/PM
date = moment(1525772511140).format('DD-MM-YYYY hh:mm:ss A');
console.log(date);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.1/moment.min.js"></script>

Native JavaScript solution (without moment.js) :

var d = new Date(1525772511140);
console.log(
  ("0" + d.getDate()).slice(-2) + '-' +
  ("0" + (d.getMonth()+1)).slice(-2) + '-' + 
  d.getFullYear() + ' ' +
  d.getHours() + ':' +
  d.getMinutes()
);

Upvotes: 6

Vikasdeep Singh
Vikasdeep Singh

Reputation: 21756

None of the answer is giving correct output.

In question expected output is 29-05-2018 9:41:51AM which is moment().format('DD-MM-YYYY HH:mm:ss A')

Below is correct answer as per the question:

let date = moment(1525772511140).format('DD-MM-YYYY HH:mm:ss A');
console.log(date);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.1/moment.js"></script>

For more information about moment formats check this link: https://momentjs.com/docs/#/parsing/special-formats/

Upvotes: 0

Vasanth
Vasanth

Reputation: 451

Try this one

moment.unix(1525772511140 / 1000).format('DD-MM-YYYY HH:mm')

Upvotes: 0

user9420984
user9420984

Reputation:

Just remove the *1000 from your statement and it works:

var timeStamp = new Date(1525772511140);
var date = moment(timeStamp).format('DD-MM-YYYY HH:mm');
console.log(date);
<script src="https://cdn.jsdelivr.net/momentjs/latest/moment.min.js"></script>

The timestamp is already in milliseconds so no need to multiply by 1000.

Upvotes: 2

justMe
justMe

Reputation: 664

Try

const date = moment(new Date(1525772511140)).toDate();

or

const date = moment(new Date(1525772511140)).format('DD-MM-YYYY HH:mm')

Upvotes: 0

Related Questions