UNPKG

date-vir

Version:

Easy and explicit dates and times.

121 lines (120 loc) 3.21 kB
import { check } from '@augment-vir/assert'; /** * Create a string based on just the date parts of a FullDate. * * **CAUTION**: this does not user locale setting. Prefer {@link toLocaleString} whenever possible. * * Example output: `'2023-12-05'` * * @category Internal */ export function toSimpleDatePartString(fullDate) { const dateParts = [ String(Math.abs(fullDate.year)).padStart(4, '0'), String(Math.abs(fullDate.month)).padStart(2, '0'), String(Math.abs(fullDate.day)).padStart(2, '0'), ]; const dateString = dateParts.join('-'); return dateString; } /** * Creates a string based on just the time parts of a FullDate. * * **CAUTION**: this does not user locale setting. Prefer {@link toLocaleString} whenever possible. * * Example output: `'05:32:21'` * * @category Internal */ export function toSimpleTimePartString(fullDate, includeSeconds) { const seconds = check.hasKey(fullDate, 'second') && includeSeconds ? String(Math.abs(fullDate.second)).padStart(2, '0') : undefined; const timeParts = [ String(Math.abs(fullDate.hour)).padStart(2, '0'), String(Math.abs(fullDate.minute)).padStart(2, '0'), seconds, ].filter(check.isTruthy); return timeParts.join(':'); } /** * Splits a FullDate up into multiple formatted string representations. * * **CAUTION**: this does not user locale setting. Prefer {@link toLocaleString} whenever possible. * * This uses numbers for everything. * * @category Formatting * @example * * ```ts * import {toDatePartStrings, utcTimezone} from 'date-vir'; * * let result = toDatePartStrings( * { * year: 2024, * month: 4, * day: 24, * hour: 6, * minute: 4, * second: 9, * millisecond: 123, * timezone: utcTimezone, * }, * {includeSeconds: true}, * ); * // outputs: * result = { * date: '2024-04-24', * time: '06:04:09', * timezone: 'UTC', * }; * ``` */ export function toDatePartStrings(fullDate, options) { return { date: toSimpleDatePartString(fullDate), time: toSimpleTimePartString(fullDate, options.includeSeconds), timezone: fullDate.timezone, }; } /** * Converts a date into a simple, unambiguous date string. * * **CAUTION**: this does not user locale setting. Prefer {@link toLocaleString} whenever possible. * * @category Formatting * @example * * ```ts * import {toSimpleString} from 'date-vir'; * * let result = toSimpleString( * { * year: 2024, * month: 4, * day: 24, * hour: 6, * minute: 4, * second: 9, * millisecond: 123, * timezone: utcTimezone, * }, * { * includeSeconds: false, * includeTimezone: false, * }, * ); * // outputs: * result = '2024-04-24 06:04'; * ``` */ export function toSimpleString(fullDate, options) { const parts = toDatePartStrings(fullDate, options); const stringParts = [ parts.date, parts.time, options.includeTimezone && `(${parts.timezone})`, ].filter(check.isTruthy); return stringParts.join(' '); }