我建立了这一小段代码(在许多SO线程的帮助下),它在过去两年中运行良好,但在2018年它错误地解释了第一周。
function getDateOutWeek(week, year, lastDay) {
var d = new Date(year, 0, 1 + (week) * 7);
var day = d.getDay();
var firstDay = d.getDate() - day + (day === 0 ? -6 : 1); // adjust when day is sunday
if (!lastDay) {
alert(new Date(d.setDate(firstDay)).toDateString());
} else {
alert(new Date(d.setDate(firstDay + 6)).toDateString());
}
}
getDateOutWeek("1", "2018");
它返回08.01.2018但应该返回01.01.2018。
它出现在第一行calculate 1 + (week) * 7 = 8
。我无法弄清楚如何在这里得到正确的值。
答案 0 :(得分:2)
为什么你一周加1? 以下代码工作正常
function getDateOutWeek(week, year, lastDay) {
var d = new Date(year, 0, week* 7);
var day = d.getDay();
var firstDay = d.getDate() - day + (day === 0 ? -6 : 1); // adjust when day is sunday
if (!lastDay) {
alert(new Date(d.setDate(firstDay)).toDateString());
} else {
alert(new Date(d.setDate(firstDay + 6)).toDateString());
}
}
getDateOutWeek("1", "2018")