简体   繁体   中英

Getting first date in week given a year,weeknumber and day number in javascript

Following is the code that calculates the week date,

//Gets the week dayNumber date against the year,week number
var getWeekDate = function (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) * 86400000);
};

The code is working fine if I give the following values,

Input:
year = 2012
weekNumber = 1
dayNumber = 0 //My week starts from monday, so I am giving it 0.

Output:
2nd,Jan 2012 //That's correct.

Input:
year = 2013
weekNumber = 1
dayNumber = 0 //My week starts from monday, so I am giving it 0.

Output:
31st,DEC 2012 //That's in-correct.

The first week of 2013 will start from 7th, Jan 2013 ieMonday but the above code is not calculating it correctly.

我建议查看ISO日历插件moment.js

That's actually accurate because day zero (Monday) of week 1 of 2013 is still part of 2012. You could use a conditional to check whether the requested day of that week is part of the year.

//Gets the week dayNumber date against the year,week number
var getWeekDate = function (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,
    ans = new Date(month + ((weekNumber - 1) * 7 + dayNumber) * 86400000);
if (weekNumber === 1 && ans.getMonth() !== 0) {
    // We're still in last year... handle appropriately
}
return ans;
};

As an aside, it wouldn't be a bad idea to put some variable checking in place. I can input week 0, week 55, and day 92 without any issues. Obviously the results are still accurate, but they may issue confusing results to those thinking in terms of calendars.

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