date-vir
Version:
Easy and explicit dates and times.
44 lines (43 loc) • 1.85 kB
JavaScript
import { omitObjectKeys } from '@augment-vir/common';
import { assertWrapDayOfMonth, assertWrapHour, assertWrapMillisecond, assertWrapMinute, assertWrapMonthNumber, assertWrapSecond, } from '@date-vir/duration';
import { DateTime } from 'luxon';
/**
* Converts a {@link FullDate} object into a Luxon DateTime library. This is only needed if you need
* complex operations on dates. It does, however, internally power a lot of date-vir functionality
* as it uses the Luxon library for conversions between timezones.
*
* @category Internal
*/
export function toLuxonDateTime(fullDateInput) {
const dateTime = DateTime.fromObject(omitObjectKeys(fullDateInput, ['timezone']), {
zone: fullDateInput.timezone,
});
/** Ignore this edge case in coverage cause idk how to trigger it. */
/* c8 ignore next 3 */
if (!dateTime.isValid) {
throw new Error(dateTime.invalidExplanation ?? undefined);
}
return dateTime;
}
/**
* Convert a Luxon DateTime object into a {@link FullDate} instance. Used internally inside of
* date-vir, but could be helpful if you need it. Usually you should prefer using the
* `createFullDate` function instead.
*
* @category Internal
*/
export function parseLuxonDateTime(dateTimeInput, forcedTimezone) {
if (!dateTimeInput.isValid) {
throw new Error(`Invalid input: '${dateTimeInput.toISO()}'`);
}
return {
day: assertWrapDayOfMonth(dateTimeInput.day),
month: assertWrapMonthNumber(dateTimeInput.month),
year: dateTimeInput.year,
hour: assertWrapHour(dateTimeInput.hour),
minute: assertWrapMinute(dateTimeInput.minute),
second: assertWrapSecond(dateTimeInput.second),
millisecond: assertWrapMillisecond(dateTimeInput.millisecond),
timezone: forcedTimezone ?? dateTimeInput.zoneName,
};
}