我如何在javascript(或jquery)中从周数和年份获取一周的第一天的日期?
示例:2013 年第 30 周
提前致谢 !
var d = new Date(year, 0, 1);
var days = ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'];
d.setDate(d.getDate() + (week * 7));
console.log(days[d.getDay()]);
使用 ISO 8601 周编号,您可以从一年中的第一周开始并添加(n - 1) * 7
天数以获得所需周的第一天。例如
function getDateByWeek(week, year) {
// Create a date for 1 Jan in required year
var d = new Date(year, 0);
// Get day of week number, sun = 0, mon = 1, etc.
var dayNum = d.getDay();
// Get days to add
var requiredDate = --week * 7;
// For ISO week numbering
// If 1 Jan is Friday to Sunday, go to next week
if (dayNum != 0 || dayNum > 4) {
requiredDate += 7;
}
// Add required number of days
d.setDate(1 - d.getDay() + ++requiredDate);
return d;
}
// Week 44 of 2021 starts on Mon 1 Nov 2021
console.log(getDateByWeek(44,2021).toString());
如果需要其他一些周编号方案,只需相应地调整开始日期。