Thrown when an input cannot be parsed into a valid date.
import atemporal from 'atemporal';import { InvalidDateError } from 'atemporal';try { // This will create an invalid instance, not throw const invalid = atemporal('not a date'); // But you can check validity if (!invalid.isValid()) { console.log('Invalid date detected'); }} catch (error) { if (error instanceof InvalidDateError) { console.error('Failed to parse date:', error.message); }}
Most Atemporal operations handle invalid dates gracefully by returning invalid instances rather than throwing errors. The InvalidDateError is thrown in specific cases like atemporal.min() and atemporal.max() when invalid dates are provided.
Thrown when an operation is attempted on an invalid atemporal instance in contexts where throwing is more appropriate than returning invalid.
import { InvalidAtemporalInstanceError } from 'atemporal';// This error is used internally and rarely thrown to users// Most operations return invalid instances instead
function processDate(input: string) { const date = atemporal(input); if (!date.isValid()) { console.error('Invalid date input:', input); return null; } return date.format('YYYY-MM-DD');}processDate('2024-03-15'); // '2024-03-15'processDate('invalid'); // null (with error logged)
function getDateOrDefault(input: string, fallback = atemporal()) { const date = atemporal(input); return date.isValid() ? date : fallback;}// Use current date if input is invalidconst date = getDateOrDefault('maybe invalid');
import { TemporalWrapper } from 'atemporal';function isValidDate( date: TemporalWrapper): date is TemporalWrapper { return date.isValid();}const date = atemporal('2024-03-15');if (isValidDate(date)) { // TypeScript knows date is valid here console.log(date.format('YYYY-MM-DD'));}
Atemporal provides several type guards for validation:
import atemporal from 'atemporal';// Check if input is valid before parsingif (atemporal.isValid('2024-03-15')) { const date = atemporal('2024-03-15');}// Check if something is already an atemporal instancefunction processDate(input: unknown) { if (atemporal.isAtemporal(input)) { // input is TemporalWrapper return input.format('YYYY-MM-DD'); } return atemporal(input as any).format('YYYY-MM-DD');}// Check if something is a durationconst duration = atemporal.duration({ days: 5 });if (atemporal.isDuration(duration)) { console.log('This is a Temporal.Duration');}// Validate timezoneconst tz = 'America/New_York';if (atemporal.isValidTimeZone(tz)) { const date = atemporal(undefined, tz);}// Validate localeif (atemporal.isValidLocale('en-US')) { atemporal.setDefaultLocale('en-US');}
function createEventDate(userInput: string) { const date = atemporal(userInput); if (!date.isValid()) { throw new Error(`Invalid date format: "${userInput}". Please use YYYY-MM-DD`); } // Ensure date is in the future if (!date.isAfter(atemporal())) { throw new Error('Event date must be in the future'); } return date;}try { const eventDate = createEventDate('2024-03-15'); console.log('Event scheduled for:', eventDate.format('MMMM Do, YYYY'));} catch (error) { console.error('Failed to create event:', error.message);}
function getUserDateTime(dateStr: string, userTimezone?: string) { // Validate and use user timezone, or fall back to UTC const timezone = userTimezone && atemporal.isValidTimeZone(userTimezone) ? userTimezone : 'UTC'; const date = atemporal(dateStr, timezone); if (!date.isValid()) { throw new Error(`Invalid date: ${dateStr}`); } return date;}// Safe to call with any timezone inputconst date1 = getUserDateTime('2024-03-15', 'America/New_York');const date2 = getUserDateTime('2024-03-15', 'Invalid/Zone'); // Uses UTC
import atemporal from 'atemporal';import customParseFormat from 'atemporal/plugins/customParseFormat';atemporal.extend(customParseFormat);interface APIResponse { createdAt: string; timezone?: string;}function parseAPIDate(response: APIResponse) { try { // Try to parse with custom format const date = atemporal.fromFormat( response.createdAt, 'DD/MM/YYYY HH:mm:ss', response.timezone ); if (!date.isValid()) { // Fallback to ISO parsing return atemporal(response.createdAt); } return date; } catch (error) { console.error('Failed to parse API date:', error); // Return current date as ultimate fallback return atemporal(); }}
// Check if a date is valid and whyconst date = atemporal('maybe-invalid');if (!date.isValid()) { console.log('Invalid date detected'); console.log('Input was:', 'maybe-invalid'); // Try to understand why by testing variations console.log('ISO format works?', atemporal('2024-03-15').isValid()); console.log('Timestamp works?', atemporal(Date.now()).isValid());}
function parseFlexibleDate(input: string): TemporalWrapper { // Try ISO format first let date = atemporal(input); if (date.isValid()) return date; // Try common formats const formats = ['DD/MM/YYYY', 'MM/DD/YYYY', 'YYYY-MM-DD']; for (const format of formats) { try { date = atemporal.fromFormat(input, format); if (date.isValid()) return date; } catch { continue; } } // Last resort: return current date console.warn(`Could not parse date: ${input}, using current date`); return atemporal();}