faisal nasir
faisal nasir

Reputation: 165

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

Upvotes: 1

Views: 1496

Answers (2)

Micah Henning
Micah Henning

Reputation: 2175

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.

Upvotes: 1

jmosbech
jmosbech

Reputation: 1128

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

Upvotes: 2

Related Questions