【前端踩过的坑】js Date的时间戳timestamp和unix时间戳有区别么?

js 获取的时间戳的方式是(new Date()).getTime,得到的例如1534982400000,然后默认就以为是moment里面的unix,然后使用moment.unx(1534982400000)来转换,后面发现居然不对。

Date.getTime 在MDN中给出的官方说法是:

The getTime() method returns the numeric value corresponding to the time for the specified date according to universal time.

getTime() always uses UTC for time representation. For example, a client browser in one timezone, getTime() will be the same as a client browser in any other timezone.

You can use this method to help assign a date and time to another Date object. This method is functionally equivalent to the valueOf() method.

下面是unix时间的定义:

什么是Unix时间戳(Unix timestamp): Unix时间戳(Unix timestamp),或称Unix时间(Unix time)、POSIX时间(POSIX time),是一种时间表示方式,定义为从格林威治时间1970年01月01日00时00分00秒起至现在的总秒数。Unix时间戳不仅被使用在Unix系统、类Unix系统中,也在许多其他操作系统中被广泛采用

乍看之下和unix的定义怎么看都一样啊,后面发现getTime获取的其实是毫秒数,而Unix时间戳只是精确到秒,因此这两者之间差了1000,因此上述moment转换的正确方式是:

moment.unix(Math.round(1534982400000/1000))

当然直接用Date作为中介也是可以的:

moment(new Date(1534982400000))
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值