日期获取自定义周开始日期的周号 [英] Date get week number for custom week start day
本文介绍了日期获取自定义周开始日期的周号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我有一个自定义的星期开始日期而不是星期一,应该如何为Date类更改getWeekNumber()原型.
How should the getWeekNumber() prototype should be changed for Date class if I have a custom week start day instead of Monday.
用于查找ISO周编号的当前代码:
Current code for finding ISO Week Number:
Date.prototype.getWeekNumber = function() {
// Create a copy of this date object
var target = new Date(this.valueOf());
// ISO week date weeks start on monday
// so correct the day number
var dayNr = (this.getDay() + 6) % 7;
// ISO 8601 states that week 1 is the week
// with the first thursday of that year.
// Set the target date to the thursday in the target week
target.setDate(target.getDate() - dayNr + 3);
// Store the millisecond value of the target date
var firstThursday = target.valueOf();
// Set the target to the first thursday of the year
// First set the target to january first
target.setMonth(0, 1);
// Not a thursday? Correct the date to the next thursday
if (target.getDay() !== 4) {
target.setMonth(0, 1 + ((4 - target.getDay()) + 7) % 7);
}
// The weeknumber is the number of weeks between the
// first thursday of the year and the thursday in the target week
return 1 + Math.ceil((firstThursday - target) / 604800000); // 604800000 = 7 * 24 * 3600 * 1000
};
推荐答案
使用现有功能并添加一个可选参数 weekstart
,该参数指定一周中的哪个工作日开始:0是星期日,1是星期一等等.默认值为星期一.
Use your existing function and add an optional parameter weekstart
that specifies on which weekday a week starts: 0 is Sunday, 1 is Monday and so on. The default value is Monday.
Date.prototype.getWeekNumber = function(weekstart) {
var target = new Date(this.valueOf());
// Set default for weekstart and clamp to useful range
if (weekstart === undefined) weekstart = 1;
weekstart %= 7;
// Replaced offset of (6) with (7 - weekstart)
var dayNr = (this.getDay() + 7 - weekstart) % 7;
target.setDate(target.getDate() - dayNr + 3);
var firstThursday = target.valueOf();
target.setMonth(0, 1);
if (target.getDay() !== 4) {
target.setMonth(0, 1 + ((4 - target.getDay()) + 7) % 7);
}
return 1 + Math.ceil((firstThursday - target) / 604800000);
};
这篇关于日期获取自定义周开始日期的周号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文