天天看點

JavaScript 日期權威指南

簡介

JavaScript通過強大的對象為我們提供日期處理功能:日期。

本文确實_不是_談論 ​​Moment.js​​ ,我認為它是處理日期的最佳庫,你應該在處理日期時幾乎總是使用它。

Date對象

Date對象執行個體表示單個時間點。

盡管被命名為Date,它也處理時間。

初始化Date對象

我們使用初始化Date對象

new Date()
      

這将建立一個指向目前時刻的Date對象。

在内部,日期以1970年1月1日(UTC)以來的毫秒數表示。這個日期很重要,因為就計算機而言,這就是一切開始的地方。

您可能熟悉UNIX時間戳:它表示自該着名日期以來經過的seconds數。

重要:UNIX時間戳的原因以秒為機關。JavaScript以毫秒為機關記錄原因。

如果我們有UNIX時間戳,我們可以使用執行個體化JavaScript Date對象

const timestamp = 1530826365
new Date(timestamp * 1000)
      

如果我們傳遞0,我們将得到一個Date對象,表示1970年1月1日(UTC)的時間:

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

最小值應該是3個參數,但是大多數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,并自動執行到目前計算機時區的轉換。

是以,總結一下,您可以通過4種方式建立新的Date對象

  • 不傳參數,建立一個表示“現在”的Date對象
  • 傳遞number,表示從格林威治标準時間1970年1月1日00:00開始的毫秒數
  • 傳遞一個字元串,代表一個日期
  • 傳遞一組參數,它們代表日期的不同部分

時區

初始化日期時,您可以傳遞時區,是以日期不會被假定為UTC,然後轉換為您當地的時區。

您可以通過以+ HOURS格式添加時區來指定時區,或者通過添加括在括号中的時區名稱來指定時區:

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

如果在括号中指定了錯誤的時區名稱,則JavaScript将預設為UTC而不會報錯。

如果您指定了錯誤的數字格式,JavaScript将報“無效日期”的錯誤。

日期轉換和格式設定

給定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版本,它們傳回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對象提供了幾種編輯日期值的方法:

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)
      

setDay和setMonth從0開始編号,是以例如March是2月。

你可以在setHours()中添加多個參數來設定分鐘,秒和毫秒:setHours(0,0,0,0) - 這同樣适用于setMinutes和setSeconds。

至于get_,set_方法也有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)
      

數月,小時,分鐘,秒和毫秒都是如此。

根據區域設定格式化日期

現代浏覽器中的支援良好國際化API(值得注意的例外:UC浏覽器)允許您翻譯日期。

它是由Intl Object 暴露出來的,這也有助于本地化數字,字元串。

我來看看Intl.DateTimeFormat()。

以下是如何使用它。

根據計算機預設區域設定格式化日期:

// "12/22/2017"
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 date1 = new Date('July 10, 2018 07:22:13')
const date2 = new Date('July 10, 2018 07:22:13')
if (date2.getTime() === date1.getTime()) {
  //dates are equal
}
      

請記住,getTime()傳回的毫秒數,是以您需要在比較中考慮時間因素。2018年7月10日07:22:13 不等于2018年7月10日。在這種情況下,您可以使用setHours(0,0,0,0)重置時間。

繼續閱讀