在 JavaScript 中,Date.getDate() 方法用于从 date 对象中检索 “day of month”。此方法不接受任何参数;它以 1 到 31 之间的数值形式返回月份中的日期,表示根据本地时区的当前日期。如果日期对象无效,则返回 NaN (Not-a-Number)。
语法
以下是 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 天。