我知道这里有很多类似的问题,但在查看了答案后,我似乎得到了意想不到的结果。
我有一个完整的日期,我需要将其转换为以毫秒为单位的unix时间戳
日期采用完整格式:Tue Dec 06 2016 10:51:47 GMT+0000 (GMT)
如果我尝试使用 unix 毫秒的 x
标识符对其进行格式化(如文档中所示),我实际上只是得到字符串 "x"
返回
时刻(日期).format('x')//= x
我在这里做错了什么?在执行此操作之前,我是否需要将 date
转换为完整格式以外的格式?为什么将参数传递给 format()
只会返回我在其中输入的格式?
最佳答案
x
选项是在 Moment 2.8.4 中添加的,任何早于该版本的版本都只会返回字母 x
而不是以毫秒为单位的 UNIX 时间。
版本2.8.4
var date = 'Tue Dec 06 2016 10:51:47 GMT+0000 (GMT)';
var unix = moment(new Date(date)).format('x');
console.log(unix);
<p>Version 2.8.4 - working !</p>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.8.4/moment.min.js"></script>
还有旧版本
var date = 'Tue Dec 06 2016 10:51:47 GMT+0000 (GMT)';
var unix = moment(new Date(date)).format('x');
console.log(unix);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.5.1/moment.min.js"></script>
请注意,新版本的 Moment 也不赞成使用随机字符串进行构造,因此
moment("Tue Dec 06 2016 10:51:47 GMT+0000 (GMT)")
会给您一个弃用通知,请参阅-> https://github.com/moment/moment/issues/1407
关于javascript - 使用 Moment.js 将日期格式化为 unix 时间戳(以毫秒为单位)返回格式字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39995763/