简体   繁体   中英

Moment.js , Invalid date time when converting epochtime

I have following code to convert epochtime to dateTime.

var newDate = moment.unix(1525168800000).format("MM/DD/YYYY");
alert(newDate);

When I check the time stamp at epochtimeconvetrer , I get back the correct time,

GMT: Tuesday, May 1, 2018 10:00:00 AM

But when I try to get the same value by parsing with moment, getting invalid date ,

09/05/50300

http://jsfiddle.net/yLc4wops/1/

Unix time is seconds from epoch . What you're passing is milliseconds from epoch . Divide the value by 1000, before passing it to the method:

moment.unix(1525168800).format("MM/DD/YYYY")
// "05/01/2018"

Alternatively, you can pass the value directly to moment() constructor, which accepts milliseconds from epoch .

moment(1525168800000).format("MM/DD/YYYY")
// "05/01/2018"

When you paste the value to the epochconverter, and try to convert it, the site clearly shows a message which says "Assuming that this timestamp is in milliseconds". See the snapshot below:

在此处输入图片说明

And that's why, it shows the result correctly.

You can also simply instantiate with the number of milliseconds from the Unix epoch, just like a Date.

var newDate = moment(1525168800000).format("MM/DD/YYYY");
alert(newDate);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM