@intlayer/core
Version:
Includes core Intlayer functions like translation, dictionary, and utility functions shared across multiple packages.
41 lines (39 loc) • 1.37 kB
JavaScript
import { getCachedIntl } from "../utils/intl.mjs";
import { internationalization } from "@intlayer/config/built";
//#region src/formatters/relativeTime.ts
/**
* Calculate the difference between 2 dates in the given unit.
*/
const diffInUnit = (from, to, unit) => {
const sec = (to.getTime() - from.getTime()) / 1e3;
switch (unit) {
case "second": return sec;
case "minute": return sec / 60;
case "hour": return sec / 3600;
case "day": return sec / 86400;
case "month": return sec / (30 * 86400);
case "quarter": return sec / (90 * 86400);
case "year": return sec / (365 * 86400);
default: return sec;
}
};
/**
* Formats the difference between two dates as a localized relative time string.
*
* @example
* relativeTime(new Date(Date.now() - 30000)); // "30 seconds ago"
*
* @example
* relativeTime("2025-01-01", new Date(), { locale: Locales.FRENCH, unit: "day" });
* // "il y a 443 jours"
*/
const relativeTime = (from, to = /* @__PURE__ */ new Date(), options) => {
const fromDate = new Date(from);
const toDate = new Date(to);
const unit = options?.unit ?? "second";
const value = diffInUnit(fromDate, toDate, unit);
return getCachedIntl(Intl.RelativeTimeFormat, options?.locale ?? internationalization?.defaultLocale, options).format(Math.round(value), unit);
};
//#endregion
export { relativeTime };
//# sourceMappingURL=relativeTime.mjs.map