JavaScript Date.setUTCMonth() 方法是一种 Date 对象方法,允许您根据协调世界时 (UTC) 设置日期的月份。此方法的返回值是 Date 对象的更新时间戳,它反映通过修改月份所做的更改。或者,我们还可以修改 date 对象的 day 值。如果 Date 对象的日期无效,该方法返回 “NaN” 作为结果。
语法
以下是 JavaScript Date.setUTCMonth() 方法的语法 -
setUTCMonth(monthValue, dateValue);
参数
此方法接受两个参数。下面描述相同 -
- monthValue - 介于 0 和 11 之间的整数,其中 0 是 1 月,11 是 12 月。
- 如果提供 -1,则会导致上一年的最后一个月。
- 如果提供 12,则会导致明年的第一个月。
- dateValue(可选)− 介于 1 和 31 之间的整数。
- 如果提供 0,则为上个月的最后一天。
- 如果提供 -1,则结果将是上个月最后一天的前一天。
- 如果提供了 32,则结果将在下个月的第一天(如果该月有 31 天)。
- 如果提供了 32,则将在下个月的第二天(如果该月有 30 天)。
返回值
此方法在修改 month 和 day (可选) 后返回表示新日期的时间戳。
示例 1
在下面的示例中,我们使用 JavaScript Date.setUTCMonth() 方法将 Date 对象的“月份”设置为 UTC 中的 10(11 月)−
<html>
<body>
<script>
let date = new Date();
date.setUTCMonth(10); // Sets the month to November
document.write(date);
</script>
</body>
</html>
输出
如果我们执行上述程序,date 对象的月份将设置为 10。
示例 2
在这里,我们根据 UTC 将月份设置为 10(11 月),将日期设置为 (25) -
<html>
<body>
<script>
let date = new Date();
date.setUTCMonth(10, 25); // Set month to November, and day to 25
document.write(date);
</script>
</body>
</html>
输出
执行后,此程序将返回更新的时间戳,其中包含提供的 “month” 和 “day” 值。
示例 3
如果我们为 monthValue 提供 “12”,则年份将递增 1 (yearValue + 1),并且 0 将用于月份 -
<html>
<body>
<script>
const date = new Date('2022-11-15'); //December 15 2022
date.setUTCMonth(12, 15); // It will be January 15 2023
document.write(date);
</script>
</body>
</html>
输出
上述程序返回时间戳为“Sun Jan 15, 2023 05:30:00 GMT+0530 (India Standard Time)”。
示例 4
如果我们为 dateValue 提供 “32”,则该月将递增 1(如果该月有 31 天),并将在下个月的第一天出现。
<html>
<body>
const date = new Date('2023-10-30'); //October 2023 has 31 days.
date.setUTCMonth(9, 32); //It will be November 1 2023.
document.write(date);
</script>
</body>
</html>
输出
上述程序返回的时间戳为“Wed Nov 01, 2023 05:30:00 GMT+0530 (India Standard Time)”。
示例 5
如果我们将无效的日期值作为参数传递给此函数,则日期将设置为“无效日期”,并且返回“NaN”作为结果 -
<html>
<body>
const date = new Date('2023-10-30'); //October 30 2023
date.setUTCMonth("asd", "vfdva"); //Invalid date
document.write(date.getUTCMonth());
</script>
</body>
</html>
输出
正如我们所看到的,“NaN” 作为输出返回。