Reputation: 1908
as the topic suggest - I'm looking to get a date when all I have is year (ex. 2014), week number (ex. 47) and day number within that week (ex. 3 - which would be Wednesday).
I've seen some similar questions the other way around, but reverse-engineering answers didn't provide any successful results.
Any ideas?
Upvotes: 0
Views: 278
Reputation: 2665
From : Getting first date in week given a year,weeknumber and day number in javascript
The answer to OP would be (if dayNumber starts from 1 (Monday) - to 7 (Sunday)):
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));
Upvotes: 0
Reputation: 239
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());
I wrote this really ugly function in case you have something against moment.js :)
Upvotes: 0
Reputation: 8590
I would highly recommend you to use the moment.js library. This is a complete date manipulation library.
Your problem would be solved by this moment().year(2014).week(47).day(3).toDate();
Upvotes: 4