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 天。

广告
© . All rights reserved.