Files
starr-philproperties/apps/api/utils/datetime.util.js
T

54 lines
2.0 KiB
JavaScript

/***********************************************************************************************************************************************************************
* File Name: datetime.util.js
* Type of Program: Utility
* Description: Pure date/time formatting helpers for backend use (emails, crons, notifications).
*
* All functions accept an optional options object: { timezone, locale }
* timezone — 'UTC' (default) | 'local' (server's local timezone)
* locale — BCP 47 tag, defaults to 'en-US'
*
* UTC is the default because emails and cron output must be unambiguous regardless
* of where the server runs. Pass { timezone: 'local' } only when displaying times
* relative to the server's configured locale (e.g. admin dashboards, server logs).
***********************************************************************************************************************************************************************/
function tzOpt(timezone) {
return timezone === 'local' ? {} : { timeZone: 'UTC' };
}
function loc(locale) {
return locale ?? 'en-US';
}
/** "June 27, 2026" */
function fmtDate(value, { timezone = 'UTC', locale } = {}) {
if (!value) return '—';
return new Date(value).toLocaleDateString(loc(locale), {
month: 'long', day: 'numeric', year: 'numeric',
...tzOpt(timezone),
});
}
/** "June 27, 2026, 3:45 PM UTC" */
function fmtDateTime(value, { timezone = 'UTC', locale } = {}) {
if (!value) return '—';
return new Date(value).toLocaleString(loc(locale), {
month: 'long', day: 'numeric', year: 'numeric',
hour: 'numeric', minute: '2-digit',
timeZoneName: 'short',
...tzOpt(timezone),
});
}
/** "3:45 PM UTC" */
function fmtTime(value, { timezone = 'UTC', locale } = {}) {
if (!value) return '—';
return new Date(value).toLocaleTimeString(loc(locale), {
hour: 'numeric', minute: '2-digit',
timeZoneName: 'short',
...tzOpt(timezone),
});
}
module.exports = { fmtDate, fmtDateTime, fmtTime };