Gordon
Gordon

Reputation: 1651

jquery/javascript- calculate days on this week given week number and year number

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

Answers (3)

kennebec
kennebec

Reputation: 104760

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)

Upvotes: 2

Raki
Raki

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

VisioN
VisioN

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

Related Questions