views:

131

answers:

4

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?

A: 
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);
};
orip
This doesn't work on dates before the first saturday of the year. Instead of returning -1, as it does now, it should return 51 or 52, depending on the previous year
Eric
Because a client wants each week, defined as starting on saturday, to be a certain holiday season. The idea would be to calculate the week number, then pull the corresponding season from an array.
Eric
+3  A: 

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
Crescent Fresh
Very close. However, I need "1 week into last year" to return 51 or 52, as it should count from the previous year's weeks
Eric
Thanks. Minor (but probably unimportant) point: most years only have 52 weeks (0-based: 51), but that should be fine for the use I intend.
Eric
@Eric: you're right. Further, rounding up (i.e. "Saturdays == end of week") means you will get 52 at the tail end of the year also. Adjusted code to always round down (i.e. "Saturdays == start of *new* week")
Crescent Fresh
A: 

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

Eric
A: 

Checkout http://www.datejs.com/

this. __curious_geek