你能否告诉我每周第一天获得第一周的最佳方式是什么?
我使用answer
中的代码function getDateOfWeek(week, y) {
var d = new Date("Jan 01, "+y+" 01:00:00");
var w = d.getTime() + 604800000 * (week-1);
var n1 = new Date(w);
var n2 = new Date(w + 518400000);
return {
dateFrom:n1,
dateTo: n2
}
}
getDateOfWeek(1,2017)返回日期: 01.01.2017,08.01.2017
但需要: 02.01.2017,08.01.2017
getDateOfWeek(53,2016)返回日期: 30.12.2016,05.01.2017
但需要: 26.12.2016,01.01.2017
你能知道如何解决它吗?
感谢。
答案 0 :(得分:3)
您需要偏移day of the week
function getDateOfWeek(week, y) {
var d = new Date("Jan 01, " + y + " 01:00:00");
var dayMs = (24 * 60 * 60 * 1000);
var offSetTimeStart = dayMs * (d.getDay() - 1);
var w = d.getTime() + 604800000 * (week - 1) - offSetTimeStart; //reducing the offset here
var n1 = new Date(w);
var n2 = new Date(w + 518400000);
return {
dateFrom: n1,
dateTo: n2
}
}
console.log(getDateOfWeek(1, 2017));
console.log(getDateOfWeek(53, 2016));