1. 程式人生 > >【前端踩過的坑】js Date的時間戳timestamp和unix時間戳有區別麼?

【前端踩過的坑】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))