datetime.toISO
v0.1.0 latestFormat a Date or millisecond timestamp to a UTC ISO 8601 string with configurable precision.
Format a Date or millisecond timestamp to a UTC ISO 8601 string with configurable precision.
Signature
function toISO(date: Date | number, opt?: ToISOOptions): string
Type Definitions:
ToISOOptions— interface
Problem
Date.toISOString() always returns millisecond precision. Different contexts need different precisions (date-only for dates, second for logs, millisecond for traces). Manual slicing of toISOString() output is brittle and error-prone.
How It Works
Uses pure UTC arithmetic (no Intl, no platform dependencies). Produces Z suffix for all time-containing precisions. Supports date, minute, second (default), and ms precision levels.
Boundaries
- UTC only. Non-UTC timezone formatting is excluded from v0.1.
- Number inputs are always treated as milliseconds (epoch ms).
- Invalid Date → TypeError.
- precision: 'date' produces no timezone suffix (just YYYY-MM-DD).
- Millisecond precision is always 3 decimal places.
Replaces
Common boilerplate this function replaces:
date.toISOString().slice(0, 10) // for date-only, or date.toISOString().slice(0, 19) + 'Z' // for second precision
Examples
datetime.toISO(new Date("2024-07-15T10:30:45.123Z")); // "2024-07-15T10:30:45Z"
datetime.toISO(new Date("2024-07-15T10:30:45.123Z"), { precision: "date" }); // "2024-07-15"
datetime.toISO(new Date("2024-07-15T10:30:45.123Z"), { precision: "ms" }); // "2024-07-15T10:30:45.123Z"
datetime.toISO(new Date("2024-07-15T10:30:45.123Z"), { precision: "minute" }); // "2024-07-15T10:30Z"
Standards
Caveats
- UTC only — non-UTC timezone formatting is excluded from v0.1 to guarantee zero Intl dependency.
- precision: 'date' omits the timezone suffix entirely (YYYY-MM-DD only).
FAQ
How to format a date as ISO 8601 in JavaScript?
datetime.toISO(date) returns a UTC ISO 8601 string at second precision by default.
How to get just the date part (YYYY-MM-DD)?
datetime.toISO(date, { precision: 'date' }) returns '2024-07-15'.
Does toISO support non-UTC timezones?
No. v0.1 is UTC only to avoid Intl dependency and ensure deterministic output.
Can I pass a number to toISO?
Yes. Numbers are treated as epoch milliseconds: datetime.toISO(1704067200000).
What is the default precision?
Second precision: '2024-07-15T10:30:45Z'. Use { precision: 'ms' } for milliseconds.