在javascript中,我怎样才能找出给定年份有多少周?从 year-dec-31 获取 weeknumber 将失败,因为这可能导致第 1 周。
这个问题计算给定年份中的周数可以回答它,但是在 JS 中是否有任何巧妙的计算方法?
在javascript中,我怎样才能找出给定年份有多少周?从 year-dec-31 获取 weeknumber 将失败,因为这可能导致第 1 周。
这个问题计算给定年份中的周数可以回答它,但是在 JS 中是否有任何巧妙的计算方法?
For the ISO 8601 Standard Weeks
function getISOWeeks(y) {
var d,
isLeap;
d = new Date(y, 0, 1);
isLeap = new Date(y, 1, 29).getMonth() === 1;
//check for a Jan 1 that's a Thursday or a leap year that has a
//Wednesday jan 1. Otherwise it's 52
return d.getDay() === 4 || isLeap && d.getDay() === 3 ? 53 : 52
}
console.log(getISOWeeks(2019))
console.log(getISOWeeks(2020))
console.log(getISOWeeks(2021))
I put this together from the two following posts.
这应该这样做=)
function getWeeks(d) {
var first = new Date(d.getFullYear(),0,1);
var dayms = 1000 * 60 * 60 * 24;
var numday = ((d - first)/dayms)
var weeks = Math.ceil((numday + first.getDay()+1) / 7) ;
return weeks
}
console.log(getWeeks(new Date("31 Dec 2012"))) // 53
如果您想坚持一周中第一年的Iso 8601 周编号
你可以稍微调整一下
function getIsoWeeks(d) {
var first = new Date(d.getFullYear(),0,4);
var dayms = 1000 * 60 * 60 * 24;
var numday = ((d - first)/dayms)
var weeks = Math.ceil((numday + first.getDay()+1) / 7) ;
return weeks
}
console.log(getWeeks(new Date("31 Dec 2016"))) // 53
console.log(getIsoWeeks(new Date("31 Dec 2016")) //52
您当然可以缩短代码并将它们全部压缩在一起,但是为了便于阅读,我声明了使用的变量,例如 dayms
你也可以看看这个JSBin例子
对于 ISO-8601 年:
方法#1:
function FunctionP(y) {
return (y + Math.floor(y/4) - Math.floor(y/100) + Math.floor(y/400)) % 7;
}
function WeekCount(y) {
var additionalWeek = (FunctionP(y) == 4 || FunctionP(y-1) == 3) ? 1 : 0;
return weekCount = 52 + additionalWeek;
}
方法 #2:来自https://www.w3resource.com/javascript-exercises/javascript-date-exercise-24.php的 GetISO8601Week 原型的逻辑
function GetMaxWeekCountOfISOYear(yyyy) {
var dec31YYYY = (new Date(yyyy, 11, 31));
var dec31Day = dec31YYYY.getDay();
return dec31Day >= 1 && dec31Day <= 3 ?
Number(GetSunday(dec31YYYY).GetISO8601Week()) :
Number(dec31YYYY.GetISO8601Week());
}
Date.prototype.GetISO8601Week = function() {
var target = new Date(this.valueOf());
var dayNr = (this.getDay() + 6) % 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);
};
function GetSunday(requestDate) {
requestDate = new Date(requestDate.setHours(0, 0, 0, 0));
var day = requestDate.getDay(),
diff = requestDate.getDate() - day;
return new Date(requestDate.setDate(diff));
}