I need to calculate the calendar week of a given date. Constraints:
- It should be properly calculated based on ISO 8601 if week starts on Monday
- It should calculate based on US standards if the week starts on Sunday
- It should be compact and fast, as the routine gets called very often
- It should work even if the year start is not January (Fiscal Year starts on October for instance)
That's what I have currently:
Date.prototype.getWeek = function() { // ISO Week
this.firstDay = 4; // ISO 8601: Week with the first thursday which contains the 4th of January
this.thursday = 4; // 0 = Sunday OR Monday (if WeekStart = "M")
if ( this.weekStart != 'M' )
{
this.firstDay = 1; // switch to US norm: Week with the 1st of January
this.thursday = 0;
}
// finding the date of the "thursday" in this week
var donnerstag = function(datum, that) {
var Do = new Date(datum.getFullYear(), datum.getMonth(),
datum.getDate() - datum.getDay() + that.thursday, 0, 0, 0);
return Do;
};
// copy date, hourly times set to 0
var Datum = new Date(this.getFullYear(),this.getMonth(),this.getDate(), 0, 0, 0);
var DoDat = donnerstag(Datum, this); // the date of the first week
var kwjahr = DoDat.getFullYear(); // the year of that date
// diff from there to this date
var DoKW1 = donnerstag(new Date(kwjahr, this.FYStart, this.firstDay), this);
//console.log(DoDat + " - " + DoKW1);
// calculate the week
var kw = Math.floor(1.5+(DoDat.getTime()-DoKW1.getTime())/86400000/7)
// adjust overflow
if ( kw < 1 )
kw = 52 + kw;
return kw;
};
Is there any more compact algorithm or can this be optimized in terms of performance?
kw
stands for the week of year,donnerstag
andDo
are Thursday. – amon Feb 19 at 11:11