Skip to content

Instantly share code, notes, and snippets.

@priezz

priezz/weeks.ts

Created Jun 20, 2019
Embed
What would you like to do?
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