UNPKG

@northguild/gmt

Version:

Date and time library for JavaScript and TypeScript, built on TC39 Temporal: time zones, DST, business days, ISO 8601 strings in and out. Never throws.

43 lines (41 loc) • 2.2 kB
import { zonedDateTimeFrom } from "../../internal/zonedWallClock.js"; import { zonedHoursInDay } from "../../internal/zonedWallClockOperations.js"; import { isValidZonedDateTime } from "../validate/isValidZonedDateTime.js"; // src/zoned/calculate/getHoursInZonedDay.ts /** * Return the number of hours in the calendar day a zoned datetime falls on. * * - Accounts for DST transitions: a spring-forward day is 23 hours, a fall-back * day is 25 hours, and a normal day is 24 hours. Zones whose DST shift isn't * a whole hour (e.g. `Australia/Lord_Howe`'s 30-minute shift) return a * fractional value instead, such as 23.5 or 24.5. * - The calculation is based on the local calendar day of the input, not the * UTC instant, and uses Temporal's `hoursInDay`: the span from that day's * `startOfDay()` to the next day's. A day whose local midnight is skipped * (e.g. `America/Santiago` on 2024-09-08, which starts at 01:00) is 23 hours. * - The day is the input's calendar date, so it can differ from the bucket * `startOfZoned(…, "day")` returns where a fall-back re-enters the previous * date: `America/Goose_Bay` at `2010-11-06T23:30:00-04:00` is in 6 November's * 24 hours here, and in a reopened 59-minute day for `startOfZoned`. * - Returns null for invalid input. * * @param value zoned ISO 8601 datetime string * @returns number of hours in the day (usually 23, 24, or 25; fractional for * non-whole-hour DST shifts), or null on invalid input * * @example getHoursInZonedDay("2024-03-31T12:00:00+01:00[Europe/London]") // 23 * @example getHoursInZonedDay("2024-04-07T12:00:00+10:00[Australia/Sydney]") // 25 * @example getHoursInZonedDay("2024-02-29T12:00:00+00:00[UTC]") // 24 * @example getHoursInZonedDay("2024-10-06T12:00:00+11:00[Australia/Lord_Howe]") // 23.5 * @example getHoursInZonedDay("2024-09-08T12:00:00-03:00[America/Santiago]") // 23 (midnight skipped) * @example getHoursInZonedDay("invalid") // null */ function getHoursInZonedDay(value) { if (!isValidZonedDateTime(value)) return null; try { return zonedHoursInDay(zonedDateTimeFrom(value)); } catch { return null; } } export { getHoursInZonedDay };