正如主题建议的那样 - 我希望得到的日期是我所拥有的年(例如2014年),周数(例如47)那个星期内的天数(例如3 - 将是星期三)。
我反过来看过一些类似的问题,但逆向工程的答案并没有提供任何成功的结果。
有什么想法吗?
答案 0 :(得分:4)
我强烈建议您使用moment.js库。这是一个完整的日期操作库。
您的问题将通过此moment().year(2014).week(47).day(3).toDate();
答案 1 :(得分:1)
function getDatebyWeek(year, week, day) {
var d = {
year: year,
month: 0,
day: 1
};
var date = new Date(d.year, d.month, d.day);
var weekCount = 0;
var month = 1;
var done = false;
while (weekCount < week) {
while (date.getMonth() < month) {
if (d.day % 7 === 0) {
weekCount++;
}
d.day++;
date.setDate(d.day);
if (weekCount === week) {
done = true;
break;
}
}
if (done) {
break;
}
month++;
d.month = month - 1;
d.day = 1;
date.setMonth(d.month);
date.setDate(d.day);
}
if (day <= d.day && day >= (d.day - 7)) {
return new Date(d.year, d.month - 1, day);
} else {
throw new Error('The day you entered is not in week ' + week);
}
}
var wk = getDatebyWeek(2014, 47, 22);
document.write(wk.toString());
&#13;
我写了这个非常丑陋的功能,以防万一你遇到反对moment.js的事情:)
答案 2 :(得分:0)
来自:Getting first date in week given a year,weeknumber and day number in javascript
OP的答案是(如果dayNumber从1(星期一)开始 - 到7(星期日)):
function getWeekDate(year, weekNumber, dayNumber) {
var date = new Date(year, 0, 10, 0, 0, 0),
day = new Date(year, 0, 4, 0, 0, 0),
month = day.getTime() - date.getDay() * 86400000;
return new Date(month + ((weekNumber - 1) * 7 + (dayNumber - 1)) * 86400000);
};
alert(getWeekDate(2014, 47, 3));