Eric
Eric

Reputation: 97575

How can I find the week which a day belongs to using javascript?

I want to find the number of the week which a day belongs to in javascript. My definition of week is the number of saturdays there have been up to that date. So the first few days of january are counted as the final week of the previous year. From there, the first saturday to the preceding friday is week 0 (0 based week counting).

Anyone know how to implement a function like this?

Upvotes: 0

Views: 502

Answers (4)

Crescent Fresh
Crescent Fresh

Reputation: 116980

This?

function week(date) {
    var firstSat = new Date(date.getFullYear(), 0, 1);
    firstSat.setDate(firstSat.getDate() + (6 - firstSat.getDay()));

    var delta = Math.floor((date - firstSat) / (7*24*60*60*1000));

    return delta < 0 ?
           delta + 52 : // first few days before 1st Sat
           delta
}

week(new Date(2009,0,1)); // Jan 1, 2009 => 51 => "1 week into last year"
week(new Date(2009,0,2)); // 51
week(new Date(2009,0,3)); // 0 => "[beginning of] week 1"
week(new Date(2009,0,10)); // 1 => "[beginning of] week 2"
week(new Date(2009,0,11)); // 1 => "still week 2"
week(new Date(2009, 9, 30)); // Fri Oct 30, 2009 => 42

Upvotes: 4

this. __curious_geek
this. __curious_geek

Reputation: 43207

Checkout http://www.datejs.com/

Upvotes: 1

Eric
Eric

Reputation: 97575

In the end, I went for:

Date.prototype.getWeek = function()
{
 var localOffset = this.getTimezoneOffset() * 60000;
 var date = new Date(this-localOffset);
 var firstSat = new Date(this);
 firstSat.setDate(1);
 firstSat.setMonth(0);
 firstSat.setDate(firstSat.getDate() + (6 - firstSat.getDay()));

 if(date < firstSat)
 {
  date.setDate(date.getDate()-7);
  return date.getWeek()+1;
 }
 else
 {
  return Math.floor((date - firstSat) / (7*24*60*60*1000));
 }
}

Which removes problems with UTC offsets

Upvotes: 0

orip
orip

Reputation: 75427

var getWeekForDate = function(date) {
  var yearStart = new Date(date.getFullYear(), 0, 0);

  // move to first Saturday
  yearStart.setDate(yearStart.getDate() + (6 - yearStart.getDay()));

  var msSinceStart = date - yearStart;
  var daysSinceStart = msSinceStart / (1000 * 60 * 60 * 24);
  var weeksSinceStart = daysSinceStart / 7;
  return Math.floor(weeksSinceStart);
};

Upvotes: 0

Related Questions