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。

廣告