gpt4 book ai didi

javascript - 添加 3 天后 moment.js 格式不正确的年份

转载 作者:行者123 更新时间:2023-11-29 18:45:55 25 4
gpt4 key购买 nike

在 javascript 中,我获取当前时刻,并向其添加 3 天。为什么年份加上 3 天仍然是 2018 年,格式为 2019 年?

当从 2 天 11 小时到 3 天 10 小时的范围内添加时,这会失败。但如果超出此范围,则工作正常。

<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="UTF-8">
<script
src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.23.0/moment.min.js">
</script>
</head>
<body>
<script>
var targ = moment();
console.log(targ.format('GGGG-MM-DD HH:mm:ss Z'));
targ.add(3, 'days');
console.log(targ.format('GGGG-MM-DD HH:mm:ss Z'));
</script>

</body>
</html>

Console.logs 显示以下内容:

2018-12-28 14:39:38 -07:00

2019-12-31 14:39:38 -07:00

最佳答案

GGGG 是 ISO 周的年份,而不是实际年份:

moment.js: Week year, week, and weekday tokens

GGGG: ISO 4 digit week year

Wikipedia: ISO week date :

[...] The ISO 8601 definition for week 01 is the week with the Gregorian year's first Thursday in it. [...]

[...] If 1 January is on a Monday, Tuesday, Wednesday or Thursday, it is in week 01. If 1 January is on a Friday, it is part of week 53 of the previous year. If it is on a Saturday, it is part of the last week of the previous year which is numbered 52 in a common year and 53 in a leap year. If it is on a Sunday, it is part of week 52 of the previous year. [...]

[...] If 31 December is on a Monday, Tuesday or Wednesday, it is in week 01 of the next year. If it is on a Thursday, it is in week 53 of the year just ending; if on a Friday it is in week 52 (or 53 if the year just ending is a leap year); if on a Saturday or Sunday, it is in week 52 of the year just ending. [...]

所以一年的最后几天可以属于下一年的第一个 ISO 周。

您正在寻找YYYY

var targ = moment();
console.log(targ.format('YYYY-MM-DD HH:mm:ss Z'));
targ.add(3, 'days');
console.log(targ.format('YYYY-MM-DD HH:mm:ss Z'));

关于javascript - 添加 3 天后 moment.js 格式不正确的年份,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53964628/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com