JavaScript Date getDay() 方法
JavaScript Date.getDay() 方法用于检索指定日期对象的"星期几"(以本地时间表示)。此方法不接受任何参数。返回值将以 0 到 6 之间的整数值表示星期几,其中 0 代表星期日,1 代表星期一,2 代表星期二……,6 代表星期六。
此方法基于本地时间(而非 UTC 时间)返回星期几。如果您需要基于 UTC 时间的星期几,请使用 getUTCDay() 方法。
语法
以下是 JavaScript Date getDay() 方法的语法 -
getDay();
此方法不接受任何参数。
返回值
此方法返回一个表示星期几的整数。
示例 1
在下面的示例中,我们演示了 JavaScript Date getDay() 方法的基本用法 -
<html> <body> <script> const CurrentDate = new Date(); const DayOfWeek = CurrentDate.getDay(); document.write(DayOfWeek); </script> </body> </html>
输出
上述程序返回星期几。
示例 2
这里,我们检索特定日期"2023 年 12 月 23 日"的星期几 -
<html>
<body>
<script>
const SpecificDate = new Date('2023-12-23');
const DayOfWeek = SpecificDate.getDay();
document.write(DayOfWeek);
</script>
</body>
</html>
输出
上述程序返回整数"6"作为给定日期的星期几。
示例 3
如果当前星期几是 0(星期日)或 6(星期六),则该程序打印"It's the weekend";否则,打印"It's a weekday" −
<html>
<body>
<script>
function isWeekend() {
const currentDate = new Date('2023-12-23');
const dayOfWeek = currentDate.getDay();
if (dayOfWeek === 0 || dayOfWeek === 6) {
document.write("It's the weekend");
} else {
document.write("It's a weekday.");
}
}
isWeekend();
</script>
</body>
</html>
输出
上述程序打印"It's the weekend",因为指定日期的星期几是 6。

