Reputation: 1651
i'm looking for a simple way to calculate the calendar days when given a week and year number using jquery/javascript.
Example: Week 18, Year 2012 would result in a list of starting with sunday
2012-04-29
2012-04-30
2012-05-01
2012-05-02
2012-05-03
2012-05-04
2012-05-05
thanks
Upvotes: 0
Views: 3403
Reputation: 104760
You need to decide what day begins a week - you specified Sunday. (ISO weeks start on Monday).
Find the first day of any week of the year by setting the date to the first day + (weeks * 7) - 7.
var year= new Date().getFullYear(), firstDay= new Date(year, 0, 1), wd= firstDay.getDay();
firstDay.setDate(1 +(-1*(wd%7)));
if(wd>3){ firstDay.setDate(firstDay.getDate()+ 7); } var week4= new Date(firstDay); week4.setDate(week4.getDate()+(4*7)- 7);
alert(week4);
returned value:(Date)
Sun Jan 20 2013 00: 00: 00 GMT-0500(Eastern Standard Time)
Upvotes: 2
Reputation: 535
jquery/javascript- calculate days on this week given week number and year number
var years = $('#yr').val();
var weeks = $('#weekNo').val();
var d = new Date(years, 0, 1);
var dayNum = d.getDay();
var diff = --weeks * 7;
if (!dayNum || dayNum > 4) {
diff += 7;
}
d.setDate(d.getDate() - d.getDay() + ++diff);
$('#result').val(d);
[Demo] [1]: https://jsfiddle.net/2bhLw084/
Upvotes: 0
Reputation: 145388
If you remake the code from this question you will get something like this:
function getDays(year, week) {
var j10 = new Date(year, 0, 10, 12, 0, 0),
j4 = new Date(year, 0, 4, 12, 0, 0),
mon = j4.getTime() - j10.getDay() * 86400000,
result = [];
for (var i = -1; i < 6; i++) {
result.push(new Date(mon + ((week - 1) * 7 + i) * 86400000));
}
return result;
}
DEMO: http://jsfiddle.net/TtmPt/
Upvotes: 3