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.

44 lines (42 loc) • 2.35 kB
import { nowInstant } from "../../internal/temporalCompat/clock.js"; import { isValidDateTimeDurationUnit } from "../../plain/validate/isValidDateTimeDurationUnit.js"; import { resolveUnixEpochUnitOptions, toUnixEpoch } from "../../internal/unixEpochValue.js"; import { readLengthUnits, subtractLengthFromStart, utcLengthFrame } from "../../internal/lengthFromNow.js"; // src/unix/get/getUnixAgo.ts /** * Return the Unix epoch before now, counted from the current time in UTC. * * - Reads the clock once, after `units` and `options` are checked. * - `units` is an object of unit amounts, such as `{ days: 90 }`. A duration string returns * null, and so does a fractional amount: write `{ hours: 36 }` for a day and a half. * - Lengths are unsigned: a negative amount returns null. `getUnixIn` counts forward. * - `{ days: 0 }` is a valid length and gives now. * - Calendar units count in UTC, so the result does not change with the server's zone, and a * missing day clamps to the end of the month, as `subtractUnix` does. For another zone's wall * clock, use `getZonedAgo` and convert. * - A `timeZone` member is not read, as `getUnixNow` reads none. * - Each call reads the clock. To pin the start, use `subtractUnix(getUnixNow(), units)`. * * @param units unit amounts, such as `{ days: 90 }`; never negative * @param options optional: the unit of the result * @returns the Unix epoch, or null for invalid `units`, a negative amount, invalid `options` or a * result outside Temporal's range * * @example getUnixAgo({ days: 90 }, { epochUnit: "seconds" }) // 1805284800 (90 days back, from a clock at 2027-06-15T12:00:00Z) * @example getUnixAgo({ days: 90 }) // 1805284800000 (milliseconds, the default) * @example getUnixAgo({ days: -1 }) // null (lengths are unsigned) * @example getUnixAgo({ fortnights: 1 } as never) // null (not a unit) * @example getUnixAgo({ days: 1 }, { epochUnit: "minutes" } as never) // null (not a UnixUnit) */ function getUnixAgo(units, options) { try { const epochUnit = resolveUnixEpochUnitOptions(options); if (epochUnit === null) return null; const amounts = readLengthUnits(units, isValidDateTimeDurationUnit); if (amounts === null) return null; return toUnixEpoch(subtractLengthFromStart(nowInstant(), amounts, utcLengthFrame()), epochUnit); } catch { return null; } } export { getUnixAgo };