1

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 i.e.Monday but the above code is not calculating it correctly.

1
  • It's because the world ends after the 21st. Commented Aug 9, 2012 at 19:35

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.