@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.
63 lines (62 loc) • 2.51 kB
JavaScript
// src/internal/gtfsTime.ts
/** Seconds in a GTFS day: the unit `dayOverflow` counts. */
const SECONDS_PER_DAY = 86400;
const SECONDS_PER_HOUR = 3600;
const SECONDS_PER_MINUTE = 60;
const HOURS_PER_DAY = SECONDS_PER_DAY / SECONDS_PER_HOUR;
/** The largest hour three digits can write. */
const GTFS_MAX_HOUR = 999;
const GTFS_TIME = /^([0-9]{1,3}):([0-9]{2}):([0-9]{2})$/;
/** Read the fields of a GTFS time, or null when the shape does not match. Checks shape only. */
function readGtfsTimeFields(value) {
const match = GTFS_TIME.exec(value);
if (match === null) return null;
const [, hh, mm, ss] = match;
return {
hours: Number(hh),
minutes: Number(mm),
seconds: Number(ss)
};
}
/**
* Read a GTFS time as the whole days past the service day and the seconds left over, or null. The
* core of `parseGtfsTime` and `isValidGtfsTime`, so the two cannot disagree.
*
* @example readGtfsTime("25:35:00") // { seconds: 5700, dayOverflow: 1 }
* @example readGtfsTime("25:60:00") // null
*/
function readGtfsTime(value) {
if (typeof value !== "string") return null;
const fields = readGtfsTimeFields(value);
if (fields === null) return null;
const { hours, minutes, seconds } = fields;
if (minutes > 59 || seconds > 59) return null;
return {
seconds: hours % HOURS_PER_DAY * SECONDS_PER_HOUR + minutes * SECONDS_PER_MINUTE + seconds,
dayOverflow: Math.floor(hours / HOURS_PER_DAY)
};
}
function pad2(n) {
return String(n).padStart(2, "0");
}
/**
* Write a GTFS time from the written time less whole 24-hour blocks and the whole days past the
* service day, or `""`. The core of `formatGtfsTime`.
*
* - `seconds` is an integer from 0 to 86399 and `dayOverflow` a non-negative integer; anything
* else, a fraction or `NaN` included, gives `""`.
* - The hour is written with at least two digits; an hour past 999 gives `""`.
*
* @example writeGtfsTime(5700, 1) // "25:35:00"
* @example writeGtfsTime(29100, 0) // "08:05:00"
* @example writeGtfsTime(0, 42) // ""
*/
function writeGtfsTime(seconds, dayOverflow) {
if (!Number.isInteger(seconds) || seconds < 0 || seconds >= SECONDS_PER_DAY) return "";
if (!Number.isInteger(dayOverflow) || dayOverflow < 0) return "";
const hours = dayOverflow * HOURS_PER_DAY + Math.floor(seconds / SECONDS_PER_HOUR);
if (hours > GTFS_MAX_HOUR) return "";
const minutes = Math.floor(seconds / SECONDS_PER_MINUTE) % 60;
return `${pad2(hours)}:${pad2(minutes)}:${pad2(seconds % SECONDS_PER_MINUTE)}`;
}
export { readGtfsTime, readGtfsTimeFields, writeGtfsTime };