日期获取自定义周开始日的周数
Date get week number for custom week start day
如果我有一个自定义的星期开始日而不是星期一,那么getWeekNumber()原型应该如何更改Date类呢?
查找ISO周号的当前代码:
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为星期一,依此类推。默认值为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);
};
相关文章:
- 如何在javascript中获取一年中的周数,其中周日是一周中的第一天
- 在Jquery或Javascript中获取两个范围或日期之间的通信周数
- 如何在javascript中根据周数、工作日和年份获取日期
- 如何在JS中获取周数
- moment JS获得一个月中的周数
- 在瞬间js中计算周数不正确
- 如何使用 javascript 获取特定年份/月份的周数
- 通过选择从开始日期算起的周数或月数来自动结束日期
- 给定特定日期(日/月/年)返回一周的开始 + 结束
- 从周数生成日期.js
- 使用 JavaScript 获取给定的日期年份、周数、一周内的日数
- 根据年份和周数创建 URL,例如“2013-W32.html”
- 一年中获得周数
- 返回周数和天数
- 美国格式的周数
- 获取4周的开始日期和结束日期
- Jquery FullCalendar,在输出中显示周数和日期名称
- 我想通过javascript或jquery显示/计算周数
- 如何在asp.net/c#中从两个开始和结束自定义日期获取周数
- 日期获取自定义周开始日的周数