JavaScript Date getDate() 方法



在 JavaScript 中,Date.getDate() 方法用於從日期物件中檢索“月份中的第幾天”。此方法不接受任何引數;它返回月份中的第幾天,這是一個介於 1 和 31 之間的數值,表示根據本地時區當前的日期。如果日期物件無效,則返回 NaN(非數字)。

語法

以下是 JavaScript Date getDate() 方法的語法:

getDate();

此方法不接受任何引數。

返回值

此方法返回一個數值,表示給定 Date 物件的月份中的第幾天 (1-31)。

示例 1

在下面的示例中,我們演示了 JavaScript Date getDate() 方法的基本用法:

<html>
<body>
<script>
   const CurrentDate = new Date();
   const DayOfMonth = CurrentDate.getDate();
   document.write(DayOfMonth);
</script>
</body>
</html>

輸出

以上程式返回當前日期的月份中的第幾天。

示例 2

在此示例中,我們檢索特定日期“2023 年 12 月 25 日”的月份中的第幾天:

<html>
<body>
<script>
   const SpecificDate = new Date('2023-12-25');
   const DayOfMonth = SpecificDate.getDate();
   document.write(DayOfMonth);
</script>
</body>
</html>

輸出

執行後,此程式返回 25 作為輸出。

示例 3

在這裡,我們使用 setDate() 方法將當前日期增加 10 天:

<html>
<body>
<script>
   const currentDate = new Date();
   currentDate.setDate(currentDate.getDate() + 10);
   const result = currentDate.getDate();
   document.write(result);
</script>
</body>
</html>

輸出

我們可以看到輸出,當前日期已增加 10 天。

廣告