转换epochtime时无效的日期时间

转换epochtime时无效的日期时间

本文介绍了Moment.js,转换epochtime时无效的日期时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码将epochtime转换为dateTime.

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

当我在

这就是为什么,它可以正确显示结果.

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.

这篇关于Moment.js,转换epochtime时无效的日期时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-28 19:41