如何使用javascript找到一天所属的周?

时间:2009-10-31 08:47:27

标签: javascript date week-number

我想在javascript中找到一天所属的星期数。我对周的定义是那个星期六以来的星期六。因此,1月的前几天被计为上一年的最后一周。从那里开始,第一个星期六到前一个星期五是第0周(0周计算)。

任何人都知道如何实现这样的功能?

4 个答案:

答案 0 :(得分:4)

此?

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

答案 1 :(得分:1)

答案 2 :(得分:0)

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

答案 3 :(得分:0)

最后,我去了:

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

这消除了UTC偏移的问题