Skip to content Skip to sidebar Skip to footer

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 dat

Solution 1:

I would suggest looking at the ISO Calendar plugin to moment.js

Solution 2:

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 numbervar getWeekDate = function (year, weekNumber, dayNumber) {

var date = newDate(year, 0, 10, 0, 0, 0),
    day = newDate(year, 0, 4, 0, 0, 0),
    month = day.getTime() - date.getDay() * 86400000,
    ans = newDate(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.

Post a Comment for "Getting First Date In Week Given A Year,weeknumber And Day Number In Javascript"