UNPKG

date-vir

Version:

Easy and explicit dates and times.

48 lines (47 loc) 2.16 kB
import { getEnumValues } from '@augment-vir/common'; import { assertHasFullDateKeys } from '../extra-utils/has-date-props.js'; import { FullDatePart } from '../full-date/full-date-parts.js'; import { toSimpleDatePartString, toSimpleTimePartString } from './simple-strings.js'; /** * Converts a {@link FullDate} instance into a string that is understood by * [`type="date"`](https://developer.mozilla.org/docs/Web/HTML/Element/input/date) or * [`type="time"`](https://developer.mozilla.org/docs/Web/HTML/Element/input/time) instances of * [`HTMLInputElement`](https://developer.mozilla.org/docs/Web/HTML/Element/input). This can * optionally include seconds as well for `type="time"`. * * This function ignores timezone, the literal stored date and time numbers are simply concatenated * into a string. If you wish to convert time zones, first call {@link toNewTimezone} on your * {@link FullDate} instance. * * @category HTML * @category Formatting */ export function toHtmlInputString(fullDate, inputType, includeSeconds) { const internalFullDate = fullDate; if (inputType === FullDatePart.Date) { assertHasFullDateKeys(internalFullDate, [ 'year', 'month', 'day', ]); return toSimpleDatePartString(internalFullDate); } else if (inputType === FullDatePart.Time) { if (includeSeconds && internalFullDate.second == undefined) { throw new Error('Tried to include seconds in the time string but no seconds were provided.'); } assertHasFullDateKeys(internalFullDate, [ 'hour', 'minute', ]); return toSimpleTimePartString(internalFullDate, !!includeSeconds); } else if (inputType === FullDatePart.DateTime) { const datePart = toHtmlInputString(fullDate, FullDatePart.Date); const timePart = toHtmlInputString(fullDate, FullDatePart.Time, includeSeconds); return `${datePart}T${timePart}`; } else { throw new Error(`Unexpected inputTyped: '${String(inputType)}'. Expected usage of FullDatePart, one of ${getEnumValues(FullDatePart).join(', ')}.`); } }