JavaScript

Convert a valid Date to an ISO timestamp

Use toISOString to serialize a valid Date as a UTC timestamp. Check that the date is valid first when the value comes from an external source.

Worked example

Node.js example · save as example.mjs and run node example.mjs

const date = new Date("2026-05-01T12:30:00-04:00");
if (Number.isNaN(date.getTime())) throw new Error("Invalid date");
console.log(date.toISOString());

How it works

The input includes an explicit offset, so the instant is unambiguous. ISO output uses Z to indicate UTC; the displayed clock time changes while the represented instant stays the same. This is useful for logs and API fields describing actual moments.

Limits and mistakes

A date-only business concept, such as a birthday, is not necessarily an instant in UTC. Avoid converting those fields blindly. Parsing nonstandard date strings is also unreliable across environments. Invalid dates cause toISOString to throw.

Check the result

Expect 2026-05-01T16:30:00.000Z. Try an invalid input and confirm it is rejected before serialization. Compare timestamps rather than localized display strings.

Sources

Reference documentation for the behavior used in this guide: