开发者

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开发者_JAVA百科 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?


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


Checkout http://www.datejs.com/


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);
};


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜