Tofu/app/tools/dates/parseWeekId.js

18 lines
856 B
JavaScript

import { getWeekId } from '#tofu/tools/dates/getWeekId.js'
import { getWeekStart } from '#tofu/tools/dates/getWeekStart.js'
const WEEK_ID_PATTERN = /^(\d{4})-W(\d{2})$/
// Inverse of getWeekId: returns the Monday 00:00:00 (local time) of the given ISO week,
// or null when the identifier is malformed or points at a week the year does not have
// (week 53 of a 52-week year).
export function parseWeekId(weekId) {
const match = typeof weekId === 'string' ? weekId.match(WEEK_ID_PATTERN) : null
if (!match) return null
const weekNumber = Number(match[2])
if (weekNumber < 1 || weekNumber > 53) return null
// January 4th is always in the first ISO week of its year.
const monday = getWeekStart(new Date(Number(match[1]), 0, 4))
monday.setDate(monday.getDate() + (weekNumber - 1) * 7)
return getWeekId(monday) === weekId ? monday : null
}