@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.
30 lines (28 loc) • 1.11 kB
JavaScript
import { isoYearString } from "../../internal/isoYearString.js";
import { zonedDateTimeFrom } from "../../internal/zonedWallClock.js";
import { isValidZonedDateTime } from "../validate/isValidZonedDateTime.js";
// src/zoned/parse/parseYearFromZoned.ts
/**
* Return the year for a given ISO 8601 zoned datetime string.
*
* - Returns the year as Temporal writes it: four digits (`"2024"`, `"0005"`), or a sign and six
* digits outside 0000–9999 (`"+010000"`, `"-000005"`).
* - Returns "" for invalid input.
*
* @param value ISO zoned datetime string
* @returns the year as four digits, or a sign and six digits outside 0000–9999, or "" on invalid input
*
* @example parseYearFromZoned("2024-03-15T14:30:45.123+00:00[UTC]") // "2024"
* @example parseYearFromZoned("0005-06-01T12:30:00+00:00[UTC]") // "0005"
* @example parseYearFromZoned("invalid") // ""
*/
function parseYearFromZoned(value) {
if (!isValidZonedDateTime(value)) return "";
try {
const zonedDateTime = zonedDateTimeFrom(value);
return isoYearString(zonedDateTime.year);
} catch {
return "";
}
}
export { parseYearFromZoned };