Date.prototype.getDay()

Date 实例的 getDay() 方法根据当地时间返回该日期是星期几,其中 0 代表星期日。对于该月的具体日期,请参阅 Date.prototype.getDate()

¥The getDay() method of Date instances returns the day of the week for this date according to local time, where 0 represents Sunday. For the day of the month, see Date.prototype.getDate().

Try it

语法

¥Syntax

js
getDay()

参数

¥Parameters

没有任何。

¥None.

返回值

¥Return value

0 到 6 之间的整数,表示根据当地时间给定日期是星期几:0 表示星期日,1 表示星期一,2 表示星期二,依此类推。如果日期是 invalid,则返回 NaN

¥An integer, between 0 and 6, representing the day of the week for the given date according to local time: 0 for Sunday, 1 for Monday, 2 for Tuesday, and so on. Returns NaN if the date is invalid.

描述

¥Description

getDay() 的返回值从零开始,这对于索引日期数组很有用,例如:

¥The return value of getDay() is zero-based, which is useful for indexing into arrays of days, for example:

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

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

但是,出于国际化的目的,你应该更喜欢使用 Intl.DateTimeFormatoptions 参数。

¥However, for the purpose of internationalization, you should prefer using Intl.DateTimeFormat with the options parameter instead.

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"

示例

¥Examples

使用 getDay()

¥Using getDay()

基于 Date 对象 xmas95 的值,weekday 变量的值为 1,因为 1995 年 12 月 25 日是星期一。

¥The weekday variable has value 1, based on the value of the Date object xmas95, because December 25, 1995 is a Monday.

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

console.log(weekday); // 1

规范

Specification
ECMAScript Language Specification
# sec-date.prototype.getday

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看