0

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

James Montagne
  • 77,516
  • 14
  • 110
  • 130
Gordon
  • 1,633
  • 3
  • 26
  • 45
  • If January 1 falls on Wednesday, when did/does week #1 start? – Marc May 03 '12 at 14:16
  • With JS, you can get the day of the week using `theDate.getDay();` You could calculate from there. – Marc May 03 '12 at 14:21
  • You need to specify which is the first week of the year. The first week, whichever day is included in the yerar? The first week that includes a monday? The first week that includes a thursday? – JotaBe May 03 '12 at 14:47

3 Answers3

3

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/

Community
  • 1
  • 1
VisioN
  • 143,310
  • 32
  • 282
  • 281
2

You need to decide what day begins a week - you specified Sunday. (ISO weeks start on Monday).

  1. Get the day of the week of Jan 1.
  2. Get the date of the closest Sunday.
  3. If Jan 1 is on a Thursday, Friday, Saturday or Sunday, the first week of the year begins a week from the last Sunday in December. Otherwise, the first week of the year begins on the last Sunday of December.
  4. 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)

kennebec
  • 102,654
  • 32
  • 106
  • 127
0

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/

Raki
  • 535
  • 4
  • 13