@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.
41 lines (39 loc) • 2.16 kB
JavaScript
import { Temporal } from "../../internal/temporal.js";
import { nowZonedDateTimeISO } from "../../internal/temporalCompat/clock.js";
import { zonedDateTimeOf } from "../../internal/zonedWallClock.js";
// src/zoned/compare/isZonedRelativeDay.ts
/**
* Return true when `value`'s local calendar day falls `offsetDays` days from
* today in `value`'s own IANA timeZone.
*
* - Subsumes `isZonedToday`/`isZonedYesterday`/`isZonedTomorrow`:
* `offsetDays: 0` is "today", `-1` is "yesterday", `1` is "tomorrow", and
* any other integer offset works the same way.
* - "Today" is resolved in `value`'s own timeZone — no separate timeZone
* argument needed, since `value` already carries its IANA timeZone. This
* is the deterministic counterpart to `isRelativeDay`, which depends on
* the system clock and system timeZone: the same instant is "today" in
* `Pacific/Apia` and "yesterday" in `Pacific/Niue`, a 24-hour spread.
* - `offsetDays` must be an integer; non-integer or non-finite values return false.
* - Returns false if `value` is invalid.
*
* @param value ISO ZonedDateTime string
* @param offsetDays integer number of days from today in `value`'s own timeZone
* @returns true if `value`'s local day is exactly `offsetDays` days from today in its own timeZone, false on invalid input
*
* @example isZonedRelativeDay("2024-03-15T10:00:00+09:00[Asia/Tokyo]", 0) // true, if today is 2024-03-15 in Asia/Tokyo
* @example isZonedRelativeDay("2024-03-14T10:00:00+09:00[Asia/Tokyo]", -1) // true, if today is 2024-03-15 in Asia/Tokyo
* @example isZonedRelativeDay("2024-03-15T10:00:00+13:00[Pacific/Apia]", 0) // true, when the same instant is "yesterday" in Pacific/Niue
* @example isZonedRelativeDay("invalid", 0) // false
*/
function isZonedRelativeDay(value, offsetDays) {
const zonedDateTime = zonedDateTimeOf(value);
if (zonedDateTime === null || !Number.isInteger(offsetDays)) return false;
try {
const target = nowZonedDateTimeISO(zonedDateTime.timeZoneId).toPlainDate().add({ days: offsetDays });
return Temporal.PlainDate.compare(zonedDateTime.toPlainDate(), target) === 0;
} catch {
return false;
}
}
export { isZonedRelativeDay };