如何获取日期和 weekofyear、year 元组之间的周数
如何获得给定日期和(周年元,年)元组之间的几周数?最好使用MOMMJS。
function getWeeksBetweenStartDate(weekOfYear, year)
const date = moment().set({
year: 1982,
month: 3,
day: 18,
hour: 0,
minute: 0,
second: 0,
});
const weeksSinceDate =
moment()
.year(year)
.isoWeek(weekOfYear)
.day(0)
.hour(0)
.minute(0)
.subtract(date)
.weeks() ;
}
function getWeeks(date) {
return getWeeksBetweenStartDate(date.isoWeeks(), date.year());
}
getWeeks(
moment().set({
year: 1982,
month: 3,
day: 21,
hour: 0,
})
) // returns 0
getWeeks(
moment().set({
year: 1982,
month: 3,
day: 23,
hour: 0,
minute: 0,
})
) // returns 1
即使两个示例日期是同一周的一部分,但返回了不同的周三角洲。
How do I get the number of weeks between a given date and (weekofyear, year) tuple? Preferably using momentjs.
function getWeeksBetweenStartDate(weekOfYear, year)
const date = moment().set({
year: 1982,
month: 3,
day: 18,
hour: 0,
minute: 0,
second: 0,
});
const weeksSinceDate =
moment()
.year(year)
.isoWeek(weekOfYear)
.day(0)
.hour(0)
.minute(0)
.subtract(date)
.weeks() ;
}
function getWeeks(date) {
return getWeeksBetweenStartDate(date.isoWeeks(), date.year());
}
getWeeks(
moment().set({
year: 1982,
month: 3,
day: 21,
hour: 0,
})
) // returns 0
getWeeks(
moment().set({
year: 1982,
month: 3,
day: 23,
hour: 0,
minute: 0,
})
) // returns 1
Even though the two example dates are part of same week, a different week delta is returned.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为代码中有几个错误:
getWeeksBetweenStartDate
中这样做.subtract(date)
,相减后,日期将变成1970年附近( UTC 纪元)。相反,您isoWeeks
方法,因为在isoWeeks
中,星期一是一周的开始。moment.locale('us')
,以确保一周始终从星期日开始。以下可能是您期望的正确代码:
There are several mistakes in the code I think:
.subtract(date)
ingetWeeksBetweenStartDate
, after subtraction, the date will become nearby 1970 (The UTC epoch). Instead, you shouldisoWeeks
method, because inisoWeeks
, Monday is the beginning of a week.moment.locale('us')
at the beginning, to ensure a week always begins at Sunday.The following maybe the correct code you expect: