Skip to content

Instantly share code, notes, and snippets.

@Dragory
Last active August 29, 2015 14:04
Show Gist options
  • Save Dragory/c5bfc339cba06e379de6 to your computer and use it in GitHub Desktop.
Save Dragory/c5bfc339cba06e379de6 to your computer and use it in GitHub Desktop.
Calculating the week number
// Converts Su-Sa (0-6) to other periods, such as Mo-Su (0-6)
function weekDayWithOffset(date, offset) {
return ((date.getDay() + 7 - offset) % 7);
}
// Calculates the week number of the given date
// Thanks to http://stackoverflow.com/a/6117889/316944
function weekNum(date) {
var refDate = new Date(date.getTime());
// Set the ref date to the week's thursday; this is due to the ISO-8601 standard that specifies
// that the week number falls on the year that has the thursday of that week.
refDate.setDate(refDate.getDate() + (4 - refDate.getDay()));
// Jan 1st
var startOfYear = new Date(date.getFullYear(), 0, 1);
// Difference between the start of the year and the input date in days
var dayDiff = ((date.getTime() - startOfYear.getTime()) / (1000 * 60 * 60 * 24));
// The weekday of Jan 1st, with the week starting on Monday
var weekDayOfStartOfYear = weekDayWithOffset(startOfYear, 1);
// Handle the day difference as if the year had started on the first day of the week Jan 1st lands on
dayDiff += weekDayOfStartOfYear;
// We floor the day difference and add 1 to it so that e.g. monday at 0.00 is its own day.
// For example, at 6.5 days passed, the number is 7 which is still week 1.
// However, at exactly 7.0 days (monday at 0.00), the number is Math.floor(7) + 1 i.e. 8, which results in week 2.
return Math.ceil((Math.floor(dayDiff) + 1) / 7);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment