跳轉到內容

JavaScript/日期

來自華夏公益教科書,開放的書籍,開放的世界



在 JavaScript 中,一個日期是一個物件。因此必須使用new運算子顯式建立它。

日期包含一個值,表示自 1970 年 1 月 1 日 UTC 以來的毫秒數。值得一提的是它不包含什麼:物件中沒有關於時區的資訊。但是,您可以將其轉換為任何任意時區的適當字串。其他方法可以選擇月份或星期幾等部分,或者您可以將該數字用於任何計算,以及更多。

建構函式

[編輯 | 編輯原始碼]

預設建構函式會建立日期物件,時間為您計算機的當前時間。

const currentMilliSeconds = new Date(); // creates a new Date object as of 'now'
alert(currentMilliSeconds);             // implicit conversion to string
alert(currentMilliSeconds.toString());  // explicit conversion to string

alert(currentMilliSeconds.valueOf());   // the real value

您可以將引數傳遞給建構函式以生成特定的日期物件。

// 1000 ms = 1 second after the beginning of JavaScript time
const pointInTime_1 = new Date(1000);
alert(pointInTime_1);
// begin of last minute in last century
const pointInTime_2 = new Date(1999, 11, 31, 23, 59);
alert(pointInTime_2);

一些常用的日期方法

靜態方法

  • Date.now():返回自 1970 年 1 月 1 日 00:00:00 UTC 以來的毫秒數(加上/減去幾小時),以您計算機的時區為準。
  • Date.UTC(<引數>):返回自 1970 年 1 月 1 日 00:00:00 UTC 以來的毫秒數。
  • Date.parse(text):由於瀏覽器差異和不一致,強烈不建議使用Date.parse()解析字串。

例項方法

  • toISOString():返回一個 ISO 8601 格式的字串。
  • getFullYear():返回完整的 4 位年份。
  • getMonth():返回當前月份。[0 - 11]
  • getDate():返回一個月中的日期。[1 - 31]
  • getDay():返回一週中的日期。[0 - 6]。星期日為 0,其他星期幾取下一個值。
  • getHours():返回基於 24 小時制的小時數 [0 - 23]。
  • getMinutes():返回分鐘。[0 - 59]
  • getSeconds():返回秒。[0 - 59]
  • getTime():返回自 1970 年 1 月 1 日以來的毫秒數。
  • valueOf():返回自 1970 年 1 月 1 日以來的毫秒數。等效於 getTime()。
  • getTimezoneOffset():返回 UTC 與本地時間之間的分鐘差。
  • setFullYear(year):在日期物件中儲存完整的 4 位年份。
  • setMonth(month, day):設定月份,以及可選的該月中的日期。'0' 是 1 月,...

'作為整數'

[編輯 | 編輯原始碼]

日期可以透過valueOf()方法或在建構函式前加上+符號返回為整數,例如,用於“播種”PRNG(偽隨機數生成器)或執行計算。

const dateAsInteger_1 = new Date().valueOf();
alert(dateAsInteger_1);

const dateAsInteger_2 = +new Date();
alert(dateAsInteger_2);

日期物件只包含一個整數。它不知道任何關於時區的資訊。只要您不以任何形式指定時區,您就在您的本地時區工作。

但有時有必要考慮時區。

// Example 1

// Create it in UTC: 27th of January, midnight
const date_1 = new Date(Date.UTC(2020, 00, 27, 0, 0, 0));
alert(date_1);

// show it in another timezone (Jakarta is +7) ...
const jakartaTime = new Intl.DateTimeFormat('en-GB', { timeZone: 'Asia/Jakarta', dateStyle: 'full', timeStyle: 'long' }).format(date_1);
alert(jakartaTime);

// ... the original value has not changed
alert(date_1);
// Example 2

// assume we are in New York timezone (-5 against UTC)
const date_2 = new Date();
console.log(date_2.toString());

// show it in another timezone (Los Angeles is -8 against UTC)
const laTime = new Intl.DateTimeFormat('en-GB', { timeZone: 'America/Los_Angeles', dateStyle: 'full', timeStyle: 'long' }).format(date_2);
console.log(laTime);

// ... the internal value has not changed
console.log(date_2.toString());

新 API:Temporal

[編輯 | 編輯原始碼]

日期物件有一些不一致和缺陷,特別是:時區支援較弱,不支援非公曆,缺少日曆功能,等等。它們可能會在後續的 JavaScript 版本中的Temporal API中得到修復。

... 在另一個頁面上提供(點選這裡)。
華夏公益教科書