Date.prototype.getDay()

Baseline 已廣泛支援

此特性已相當成熟,可在許多裝置和瀏覽器版本上使用。自 ⁨2015 年 7 月⁩以來,各瀏覽器均已提供此特性。

getDay() 方法 Date 例項,根據本地時間返回該日期的星期幾,其中 0 代表星期日。關於月份中的日期,請參閱 Date.prototype.getDate()

試一試

const birthday = new Date("August 19, 1975 23:15:30");
const day1 = birthday.getDay();
// Sunday - Saturday : 0 - 6

console.log(day1);
// Expected output: 2

語法

js
getDay()

引數

無。

返回值

一個整數,介於 0 和 6 之間,代表給定日期根據本地時間的星期幾:0 表示星期日,1 表示星期一,2 表示星期二,依此類推。如果日期 無效,則返回 NaN

描述

getDay() 的返回值是零基索引的,這對於索引星期陣列很有用,例如:

js
const valentines = new Date("1995-02-14");
const day = valentines.getDay();
const dayNames = ["Sunday", "Monday", "Tuesday" /* , … */];

console.log(dayNames[day]); // "Monday"

但是,為了國際化,您應該優先使用 Intl.DateTimeFormatoptions 引數。

js
const options = { weekday: "long" };
console.log(new Intl.DateTimeFormat("en-US", options).format(valentines));
// "Monday"
console.log(new Intl.DateTimeFormat("de-DE", options).format(valentines));
// "Montag"

示例

使用 getDay()

變數 weekday 的值為 1,這是基於 Date 物件 xmas95 的值,因為 1995 年 12 月 25 日是星期一。

js
const xmas95 = new Date("1995-12-25T23:15:30");
const weekday = xmas95.getDay();

console.log(weekday); // 1

規範

規範
ECMAScript® 2026 語言規範
# sec-date.prototype.getday

瀏覽器相容性

另見