Error Handling
date-wiz never throws on invalid input. Every function that receives a bad date returns a configurable fallback value instead.
Default behaviour
Section titled “Default behaviour”By default, invalid dates return the string "Invalid Date":
import { format, getRelativeTime, smartFormat } from 'date-wiz';
format('not a date', 'YYYY') // → "Invalid Date"getRelativeTime('not a date') // → "Invalid Date"smartFormat('not a date') // → "Invalid Date"parse() is the exception — it returns null by default:
import { parse } from 'date-wiz';
parse('not a date') // → nullCustom fallbacks
Section titled “Custom fallbacks”Every function accepts a fallback option:
import { format, getRelativeTime, smartFormat } from 'date-wiz';
// Return a dashformat('bad', 'YYYY', undefined, { fallback: '—' }) // → "—"getRelativeTime('bad', { fallback: '—' }) // → "—"smartFormat('bad', { fallback: '—' }) // → "—"
// Return null (renders nothing in React)format('bad', 'YYYY', undefined, { fallback: null }) // → ""getRelativeTime('bad', { fallback: null }) // → ""
// Return empty string explicitlyformat('bad', 'YYYY', undefined, { fallback: '' }) // → ""Guarding parse() results
Section titled “Guarding parse() results”parse() returns Date | null. Always guard before using:
import { parse, format } from 'date-wiz';
function displayDate(input: string): string { const d = parse(input); if (!d) return 'Invalid date'; return format(d, 'LL');}Or use a custom fallback at the parse stage:
const d = parse(userInput) ?? new Date(); // fall back to nowWhat counts as invalid?
Section titled “What counts as invalid?”date-wiz considers a date invalid when isNaN(date.getTime()) — the same condition JavaScript’s Date uses internally. This includes:
new Date('garbage') // Invalid Datenew Date(undefined) // Invalid Datenew Date(NaN) // Invalid Datenew Date('') // Invalid Date (in most runtimes)It does not include dates that are technically valid but unusual:
new Date(0) // ✅ Valid — Unix epochnew Date('1800-01-01') // ✅ Valid — historical datenew Date('9999-12-31') // ✅ Valid — far futureTypeScript and nullability
Section titled “TypeScript and nullability”The fallback type is string | null. TypeScript ensures you handle both cases:
import { format } from 'date-wiz';import type { FormatOptions } from 'date-wiz';
const opts: FormatOptions = { fallback: null };const result: string = format('bad', 'YYYY', undefined, opts);// result is "" when fallback is null — safe to render