Tofu/app/tools/dates/getWeekId.js

18 lines
939 B
JavaScript

import { getWeekStart } from '#tofu/tools/dates/getWeekStart.js'
const WEEK_IN_MS = 7 * 24 * 60 * 60 * 1000
// Returns the ISO 8601 week identifier of `date`, for example "2026-W38".
// ISO 8601 rule: a week belongs to the year of its Thursday, so the week-year
// can differ from the calendar year around January 1st.
export function getWeekId(date) {
const thursday = getWeekStart(date)
thursday.setDate(thursday.getDate() + 3)
const weekYear = thursday.getFullYear()
// January 4th is always in the first ISO week, so its Thursday is the first Thursday.
const firstThursday = getWeekStart(new Date(weekYear, 0, 4))
firstThursday.setDate(firstThursday.getDate() + 3)
// Rounding absorbs the one hour a daylight saving change adds to or removes from the span.
const weekNumber = 1 + Math.round((thursday.getTime() - firstThursday.getTime()) / WEEK_IN_MS)
return `${weekYear}-W${String(weekNumber).padStart(2, '0')}`
}