问题
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