简体   繁体   中英

Get date given year, week number, day number within week with JavaScript

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?

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();

 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 :)

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)); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM