-
-
Save yiweig/915e4ba6638f4dcf4822 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// `date` must be a Date object, otherwise you may | |
// need to change lines 6 and 10 to account | |
// for a different data type. | |
function(date) { | |
// Create a copy of this date object | |
var target = new Date(date.valueOf()); | |
// ISO week date weeks start on Monday | |
// so correct the day number | |
var dayNumber = (date.getDay() + 6) % 7; | |
// Set the target to the Thursday of this week so the | |
// target date is in the right year | |
target.setDate(target.getDate() - dayNumber + 3); | |
// ISO 8601 states that week 1 is the week | |
// with January 4th in it | |
var janFourth = new Date(target.getFullYear(), 0, 4); | |
// Number of days between target date and January 4th | |
// 1000 ms/sec * 60 sec/min * 60 min/hour * 24 hour/day = 86400000 ms/day | |
var dayDiff = (target - janFourth) / 86400000; | |
// Calculate week number: Week 1 (January 4th) plus the | |
// number of weeks between target date and January 4th | |
var weekNumber = 1 + Math.ceil(dayDiff / 7); | |
return weekNumber; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment