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.

76 lines (74 loc) • 2.59 kB
import { Temporal } from "./temporal.js"; import { nowInstant } from "./temporalCompat/clock.js"; import { ENGLISH_MONTH_NAMES, ENGLISH_WEEKDAY_NAMES } from "./englishCalendarNames.js"; // src/internal/httpDateFields.ts const RFC850_DATE = /^(Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (\d{2})-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\d{2}) (\d{2}):(\d{2}):(\d{2}) GMT$/; const ASCTIME_DATE = /^(Mon|Tue|Wed|Thu|Fri|Sat|Sun) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\d{2}| \d) (\d{2}):(\d{2}):(\d{2}) (\d{4})$/; const LONG_WEEKDAY_NAMES = [ "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday" ]; function monthNumber(name) { return ENGLISH_MONTH_NAMES.indexOf(name) + 1; } function resolveTwoDigitYear(twoDigits, fields) { const limit = nowInstant().toZonedDateTimeISO("UTC").add({ years: 50 }).toPlainDateTime(); const isBeyondLimit = (year) => Temporal.PlainDateTime.compare({ ...fields, year }, limit) > 0; let year = Math.floor(limit.year / 100) * 100 + twoDigits; while (isBeyondLimit(year)) year -= 100; while (!isBeyondLimit(year + 100)) year += 100; return year; } /** * Read the fields of an RFC 9110 obsolete HTTP-date: `rfc850-date` or * `asctime-date`. IMF-fixdate is read with the exported `httpDate` pattern. * * - Shape checks only: the calendar date and the day of week are left to the * caller (`Temporal.PlainDateTime.from` with `overflow: "reject"`). * - An `rfc850-date` reads the clock (`nowInstant()`) to place its * two-digit year; that call throws if the clock cannot be read. * * @param value candidate obsolete HTTP-date * @returns the fields, or `null` when `value` is neither obsolete format */ function readObsoleteHttpDate(value) { const rfc850 = RFC850_DATE.exec(value); if (rfc850 !== null) { const [, dayName, day, month, year, hour, minute, second] = rfc850; const fields = { month: monthNumber(month), day: Number(day), hour: Number(hour), minute: Number(minute), second: Number(second) }; return { ...fields, dayOfWeek: LONG_WEEKDAY_NAMES.indexOf(dayName) + 1, year: resolveTwoDigitYear(Number(year), fields) }; } const asctime = ASCTIME_DATE.exec(value); if (asctime !== null) { const [, dayName, month, day, hour, minute, second, year] = asctime; return { dayOfWeek: ENGLISH_WEEKDAY_NAMES.indexOf(dayName) + 1, year: Number(year), month: monthNumber(month), day: Number(day), hour: Number(hour), minute: Number(minute), second: Number(second) }; } return null; } export { readObsoleteHttpDate };