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