从星期日开始,以周为单位获取周数

时间:2017-08-27 23:47:36

标签: javascript jquery function date time

我目前有这个代码,我可以通过添加和减去按钮获得该周的开始/结束日期的周数:

Date.prototype.getWeekNumber = function() {
  var d = new Date(Date.UTC(this.getFullYear(), this.getMonth(), this.getDate()));
  var dayNum = d.getUTCDay() || 7;
  d.setUTCDate(d.getUTCDate() + 4 - dayNum);
  var yearStart = new Date(Date.UTC(d.getUTCFullYear(), 0, 1));
  return Math.ceil((((d - yearStart) / 86400000) + 1) / 7);
};

var curr;
weekReset();

function display() {
  start.textContent = curr;
  end.textContent = endOfWeek(curr);
  week.textContent = ("Week " + curr.getWeekNumber());
}

function weekReset() {
  curr = startOfWeek(new Date());
  display();
}

function startOfWeek(date) {
  var start = new Date(date);
  start.setHours(0, 0, 0, 0);
  start.setDate(start.getDate() - start.getDay());
  return start;
}

function endOfWeek(date) {
  date = startOfWeek(date);
  date.setDate(date.getDate() + 6);
  return date;
}

function weekPlus(weeks) {
  curr.setDate(curr.getDate() + 7 * weeks);
  display();
}
<div id="start">start</div>
<div id="end">end</div>
<div id="week">week</div>
<button onclick="weekReset()">current</button>
<button onclick="weekPlus(1)">add</button>
<button onclick="weekPlus(-1)">substract</button>

问题在于它显示当前的周数为 34 ;

Sun 8月27日开始

星期六02月02日结束

......这应该是周数 35

那么如何更改此功能以将星期日计算为一周的第一天和星期六作为一周的最后一天呢?

感谢任何帮助。

2 个答案:

答案 0 :(得分:1)

您的代码d.setUTCDate(d.getUTCDate() + 4 - dayNum);将您的日期设置回三天前。我认为这就是你获得前一周数字的原因。我检查了删除代码,它工作正常。

答案 1 :(得分:1)

您的问题在这里:

var dayNum = d.getUTCDay() || 7;
d.setUTCDate(d.getUTCDate() + 4 - dayNum);

该代码用于ISO周,并将星期日的天数调整为7,并将日期设置为星期四,星期一为星期一。

你想要星期天到星期六,想要星期天这一周,所以请使用:

var dayNum = d.getUTCDay();
d.setUTCDate(d.getUTCDate() - dayNum);

可以简化为:

d.setUTCDate(d.getUTCDate() - d.getUTCDay());

 Date.prototype.getWeekNumber = function () {
        var d = new Date(Date.UTC(this.getFullYear(), this.getMonth(), this.getDate()));
        d.setUTCDate(d.getUTCDate() - d.getUTCDay());
        var yearStart = new Date(Date.UTC(d.getUTCFullYear(), 0, 1));
        return Math.ceil((((d - yearStart) / 86400000) + 1) / 7);
    };
    
var c = new Date(2017,7,26);
console.log(c.getWeekNumber() + ':' + c.toString());
var d = new Date(2017,7,27);
console.log(d.getWeekNumber() + ':' + d.toString());