Moment.js , Invalid date time when converting epochtime

╄→尐↘猪︶ㄣ 提交于 2021-02-08 09:30:17

问题


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/


回答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.




回答2:


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);


来源:https://stackoverflow.com/questions/51925837/moment-js-invalid-date-time-when-converting-epochtime

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!