JavaScript Dates 終極指南

在 JavaScript 中處理日期可能會很複雜,咱們一塊兒學習 Dates 全部的怪癖並掌握如何使用它。

簡介

在 JavaScript 中處理日期可能會很複雜,不管開發者技術如何,每每都會感到痛苦。javascript

image.png

JavaScript 經過一個強大的Date對象對咱們提供了日期處理功能。java

DATE 對象

Date 對象實例表示單個時間點.git

儘管名爲 Date, 它一樣被用來處理時間。github

初始化 Date 對象

咱們經過下述代碼初始化一個 Date 對象:express

new Date()

上述代碼建立了一個表徵當前時刻的日期對象。瀏覽器

在內部, 日期表示自 1970年1月1日 (UTC) 起到如今的毫秒數 。這個時間很重要, 由於就計算機而言, 這是其起始之時。ide

您可能熟悉 UNIX 時間戳: 這表示自該著名日期以來過去的秒數。學習

注意 UNIX 時間戳 以秒爲單位,JavaScript 日期以 毫秒爲單位

若是咱們有一個 UNIX 時間戳,咱們能夠經過下述方法初始化一個 JavaScript 日期對象:ui

const timestamp = 1530826365
new Date(timestamp * 1000)

若是咱們傳入的是0,咱們將會得到表示 Jan 1st 1970 (UTC) 這個時間點的日期。this

new Date(0)

若是咱們傳入的是一個字符串而非一個數值,那麼 Date 對象會使用 parse 方法來判明你傳入的到底是哪一個日期,如:

new Date('2018-07-22')
new Date('2018-07') //July 1st 2018, 00:00:00
new Date('2018') //Jan 1st 2018, 00:00:00
new Date('07/22/2018')
new Date('2018/07/22')
new Date('2018/7/22')
new Date('July 22, 2018')
new Date('July 22, 2018 07:22:13')
new Date('2018-07-22 07:22:13') // 在 Safari11.1.2 上不能識別
new Date('2018-07-22T07:22:13')
new Date('25 March 2018')
new Date('25 Mar 2018')
new Date('25 March, 2018')
new Date('March 25, 2018')
new Date('March 25 2018')
new Date('March 2018') //Mar 1st 2018, 00:00:00
new Date('2018 March') //Mar 1st 2018, 00:00:00
new Date('2018 MARCH') //Mar 1st 2018, 00:00:00
new Date('2018 march') //Mar 1st 2018, 00:00:00

這裏很靈活。您能夠在月份或天數內添加或省略前導零.

須要注意 月/日 的位置,不然可能會把月份解析爲日期。

使用 Date.parse 也能夠處理字符串:

Date.parse('2018-07-22')
Date.parse('2018-07') //July 1st 2018, 00:00:00
Date.parse('2018') //Jan 1st 2018, 00:00:00
Date.parse('07/22/2018')
Date.parse('2018/07/22')
Date.parse('2018/7/22')
Date.parse('July 22, 2018')
Date.parse('July 22, 2018 07:22:13')
Date.parse('2018-07-22 07:22:13')
Date.parse('2018-07-22T07:22:13')

Date.parse 會返回毫秒錶示的時間戳而非一個 Date 對象

你還能夠按照順序傳入值來表示日期的每一部分,參數順序以下:年份,月份(從0開始),日期,小時,分鐘,秒,毫秒

new Date(2018, 6, 22, 7, 22, 13, 0)
new Date(2018, 6, 22)

最少須要傳入三個參數,不過大多 JavaScript 引擎也能夠解析少於 三個參數的狀況

new Date(2018, 6) //Sun Jul 01 2018 00:00:00 GMT+0200 (Central European Summer Time)
new Date(2018) //Thu Jan 01 1970 01:00:02 GMT+0100 (Central European Standard Time)

上述代碼的最終結果是依賴於你的電腦的時區的相對值。這意味着傳入相同的參數在不一樣電腦上可能會有不一樣的結果。

JavaScript 在沒有任何有關時區的信息的狀況下, 會將日期視爲 UTC, 結果會自動針對當前的計算機時區進行轉換。

總結一下,有四種方法可讓你建立一個新的 Date 對象:

  • 不傳參數,會基於當前時間建立 Date 對象;
  • 傳入表明自 1 Jan 1970 00:00 GMT 過去的毫秒數的數值;
  • 傳入表明日期的字符串;
  • 傳入一系列分別表明各項的參數;

時區

初始化日期時, 您也能夠傳入時區, 此時日期不假定爲 UTC, 而後轉換爲本地時區。

能夠經過 +HPURS 格式 或者添加時區名稱的方式傳入時區。

new Date('July 22, 2018 07:22:13 +0700')
new Date('July 22, 2018 07:22:13 (CET)')

若是在解析時傳入了錯誤的時區名稱,JavaScript 會默認使用 UTC 並不會報錯。

若是傳入了錯誤格式的數值,JavaScript會報 Invaild Date 錯誤。

日期轉換和格式化

對於一個給定的日期對象,存在不少方法能夠基於該日期生產字符串

const date = new Date('July 22, 2018 07:22:13')

date.toString() // "Sun Jul 22 2018 07:22:13 GMT+0200 (Central European Summer Time)"
date.toTimeString() //"07:22:13 GMT+0200 (Central European Summer Time)"
date.toUTCString() //"Sun, 22 Jul 2018 05:22:13 GMT"
date.toDateString() //"Sun Jul 22 2018"
date.toISOString() //"2018-07-22T05:22:13.000Z" (ISO 8601 format)
date.toLocaleString() //"22/07/2018, 07:22:13"
date.toLocaleTimeString()    //"07:22:13"
date.getTime() //1532236933000
date.getTime() //1532236933000

Date 對象的 GETTER 方法

Date 對象提供了幾種檢查其值的方法。這些方法的結果都都取決於計算機的當前時區

const date = new Date('July 22, 2018 07:22:13')

date.getDate() //22
date.getDay() //0 (0 means sunday, 1 means monday..)
date.getFullYear() //2018
date.getMonth() //6 (starts from 0)
date.getHours() //7
date.getMinutes() //22
date.getSeconds() //13
date.getMilliseconds() //0 (not specified)
date.getTime() //1532236933000
date.getTimezoneOffset() //-120 (will vary depending on where you are and when you check - this is CET during the summer). Returns the timezone difference expressed in minutes

上述方法存在對應的獲取 UTC 時間的版本:

date.getUTCDate() //22
date.getUTCDay() //0 (0 means sunday, 1 means monday..)
date.getUTCFullYear() //2018
date.getUTCMonth() //6 (starts from 0)
date.getUTCHours() //5 (not 7 like above)
date.getUTCMinutes() //22
date.getUTCSeconds() //13
date.getUTCMilliseconds() //0 (not specified)

編輯 Date 對象

Date 對象提供了若干編輯日期值得方法

const date = new Date('July 22, 2018 07:22:13')

date.setDate(newValue)
date.setDay(newValue)
date.setFullYear(newValue) //note: avoid setYear(), it's deprecated
date.setMonth(newValue)
date.setHours(newValue)
date.setMinutes(newValue)
date.setSeconds(newValue)
date.setMilliseconds(newValue)
date.setTime(newValue)
date.setTimezoneOffset(newValue)
setDaysetMonth 都從數值 0 開始 處理,好比三月應該爲數值 2

這裏有一個冷知識: 這些方法會 「重疊」, 因此好比說若是你使用了 date.setHours (48), 結果會影響到天。

還有一個冷知識,你能夠爲 setHours() 方法傳入多個參數,用以設置分鐘,秒,毫秒,如setHours(0, 0, 0, 0), setMinutessetSeconds 存在相似的狀況。

相似於衆多獲取日期的方法同樣,設置日期的方法也存在對於的 UTC 版本:

const date = new Date('July 22, 2018 07:22:13')

date.setUTCDate(newalue)
date.setUTCDay(newValue)
date.setUTCFullYear(newValue)
date.setUTCMonth(newValue)
date.setUTCHours(newValue)
date.setUTCMinutes(newValue)
date.setUTCSeconds(newValue)
date.setUTCMilliseconds(newValue)

獲取當前的時間戳

若是你想獲取以毫秒爲單位的當前時間戳,推薦使用下述方法:

Date.now()

而不是

new Date().getTime()

JavaScript 始終嘗試獲取最準確的結果

上面已經提到過,你傳入的天數會影響到總的日期,這不會報錯,會直接更新月份

new Date(2018, 6, 40) //Thu Aug 09 2018 00:00:00 GMT+0200 (Central European Summer Time)

上述現象在日期,小時,分鐘,秒以及毫秒一樣生效

依據本地狀況格式化日期

Internationalization API 在現代瀏覽器中有很好的支持(除了 UC瀏覽器),容許你轉換日期。

本地化方法經過,經過 Int1 對象暴露,這個對象還能夠用來幫助本地化數值,字符串以及貨幣。

這裏咱們用到的是 Intl.DateTimeFormat()

咱們能夠經過下述方法來依據電腦的本地狀況格式化一個日期:

const date = new Date('July 22, 2018 07:22:13')
new Intl.DateTimeFormat().format(date) //"22/07/2018" in my locale

也能夠依據不一樣的時區格式化日期:

new Intl.DateTimeFormat('en-US').format(date) //"7/22/2018"

Intl.DateTimeFormat 方法還接收一個可選的參數用以自定義輸出格式,能夠用來展現 小時,分鐘和秒

const options = {
  year: 'numeric',
  month: 'numeric',
  day: 'numeric',
  hour: 'numeric',
  minute: 'numeric',
  second: 'numeric'
}

new Intl.DateTimeFormat('en-US', options).format(date) //"7/22/2018, 7:22:13 AM"
new Intl.DateTimeFormat('it-IT', options2).format(date) //"22/7/2018, 07:22:13"

點擊這個連接能夠查看全部能夠用到的屬性

兩個日期的對比

能夠經過 Date.getTime() 獲取兩個日期之間的差異

const date1 = new Date('July 10, 2018 07:22:13')
const date2 = new Date('July 22, 2018 07:22:13')
const diff = date2.getTime() - date1.getTime() //difference in milliseconds

一樣也能夠經過這個方法檢測兩個日期是否相同:

const date2 = new Date('July 10, 2018 07:22:13')
if (date2.getTime() === date1.getTime()) {
  //dates are equal
}

須要注意的是,getTime() 方法比較的是毫秒,因此 July 10, 2018 07:22:13July 10, 2018 並不相等。不過你能夠經過 setHours(0, 0, 0, 0) 來重置時間。

一些有用的連接

相關文章
相關標籤/搜索