Skip to content

Instantly share code, notes, and snippets.

@priezz
Created June 20, 2019 05:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save priezz/cc59cf7452e6e53e5b46a2be7b3fd0d9 to your computer and use it in GitHub Desktop.
Save priezz/cc59cf7452e6e53e5b46a2be7b3fd0d9 to your computer and use it in GitHub Desktop.
Week number calculation
/* For a given date, get the ISO week number.
Algorithm is to find nearest Thursday, it's year is the year of the week number.
Then get weeks between that date and the first day of that year.
NOTE: Dates in one year can be weeks of previous or next year, overlap is up to 3 days.
e.g. 2014/12/29 is Monday in week 1 of 2015, 2012/1/1 is Sunday in week 52 of 2011
*/
export function getWeekNumber(d: Date) {
// Copy date so don't modify original
d = new Date(Date.UTC(d.getFullYear(), d.getMonth(), d.getDate()))
// Set to nearest Thursday: current date + 4 - current day number
d.setUTCDate(d.getUTCDate() + 4 - (d.getUTCDay() || 7)) // Make Sunday's day number 7
const yearStart = new Date(Date.UTC(d.getUTCFullYear(), 0, 1)) // Get first day of year
// Calculate full weeks to nearest Thursday
const weekNo = Math.ceil((((d.valueOf() - yearStart.valueOf()) / 86400000) + 1) / 7)
return [d.getUTCFullYear(), weekNo]
}
export function nowDetails() {
const now = new Date()
const [weekYear, week] = getWeekNumber(now)
return {
day: now.getDate(),
month: now.getMonth(),
week,
weekYear,
year: now.getFullYear(),
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment