@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.
47 lines (45 loc) • 2.35 kB
JavaScript
import { nowZonedDateTimeISO } from "../../internal/temporalCompat/clock.js";
import { getSystemTimeZone } from "../../zoned/get/getSystemTimeZone.js";
import { isValidDateTimeDurationUnit } from "../validate/isValidDateTimeDurationUnit.js";
import { readLengthUnits } from "../../internal/lengthFromNow.js";
// src/plain/get/getDateTimeAgo.ts
/**
* Return the PlainDateTime before now, as an ISO string, counted from the current time.
*
* - Reads the clock once, after `units` is checked.
* - `units` is an object of unit amounts (years to nanoseconds), such as `{ days: 90 }`. A duration
* string returns "". A fractional amount returns "": write `{ hours: 36 }` for a day and a half.
* - Lengths are unsigned: a negative amount returns "". `getDateTimeIn` is the other direction.
* - `{ days: 0 }` is a valid length and gives now.
* - Counts on the wall clock of the system time zone. It knows nothing of daylight saving, so the
* result can name a time that does not exist there; `getZonedAgo` gives a real instant.
* - Whole seconds, floored. The sub-second route is `subtractDateTime(getNow(), units)`.
* - A missing day clamps to the end of the month: 31 March minus a month is
* 28 February, or 29 in a leap year.
* - Each call reads the clock. To pin the start, use `subtractDateTime(getNow(), units)`.
* - Examples read the clock at 2027-06-15T12:00:00Z, with the system time zone UTC.
*
* @param units unit amounts, such as `{ days: 90 }`; never negative
* @returns ISO PlainDateTime string in whole seconds, or "" for invalid `units`, a negative amount,
* an unavailable system zone or a result outside Temporal's range
*
* @example getDateTimeAgo({ days: 90 }) // "2027-03-17T12:00:00"
* @example getDateTimeAgo({ months: 1 }) // "2027-05-15T12:00:00"
* @example getDateTimeAgo({ hours: 36 }) // "2027-06-14T00:00:00"
* @example getDateTimeAgo({ days: -1 }) // "" (lengths are unsigned)
*/
function getDateTimeAgo(units) {
try {
const amounts = readLengthUnits(units, isValidDateTimeDurationUnit);
if (amounts === null) return "";
const timeZone = getSystemTimeZone();
if (!timeZone) return "";
return nowZonedDateTimeISO(timeZone).toPlainDateTime().subtract(amounts, { overflow: "constrain" }).toString({
smallestUnit: "second",
roundingMode: "floor"
});
} catch {
return "";
}
}
export { getDateTimeAgo };