API timestamp validation
Validate UTC timestamps in JSON, REST, or event payloads before application logic consumes them.
Zod · Module
z.iso.datetime() validates strings against a strict subset of ISO 8601. By default it accepts UTC-style datetimes, rejects timezone offsets and local datetimes, and can allow offsets with { offset: true }.
z.iso.datetime() builds a string schema for a strict subset of ISO 8601. Its default form requires a timezone designator such as Z and rejects offsets and local, timezone-less datetimes; pass { offset: true } when offsets should be accepted.
z.iso.datetime(options?)| Name | Type | Description |
|---|---|---|
options | object | Options controlling ISO datetime validation; the documented option is offset, which enables timezone offsets when true. |
A Zod string schema that validates ISO datetime strings.
Z suffix pass the default schema.offset: true to permit timezone offsets.offset option is enabled.import { z } from "zod";
const timestamp = z.iso.datetime();
console.log(timestamp.safeParse("2024-06-01T12:30:00Z").success); // true
console.log(timestamp.safeParse("2024-06-01T12:30:00+02:00").success); // falseCreates a strict ISO-style datetime string schema and checks two inputs, one using UTC and one using a timezone offset.
Validate UTC timestamps in JSON, REST, or event payloads before application logic consumes them.
Accept timestamps emitted by clients that include numeric timezone offsets.
Preserve variable-length fractional seconds while validating timestamp structure.
z.iso.datetime() validate by default?It validates strings against Zod’s strict ISO 8601 datetime subset. With default options, a UTC suffix such as Z is accepted, while offsets and local datetimes are rejected.
Follow-up: How would you accept an offset such as +02:00? Construct the schema with z.iso.datetime({ offset: true }).
The offset option controls whether timezone offsets are accepted. Setting it to true allows values such as 2020-01-01T06:15:00+02:00; it does not merely change the output type.
Follow-up: What happens to a local datetime without an offset? It remains invalid under the default schema because local datetimes are not allowed.
It accepts fractional seconds, including examples with three and six digits. The documentation also states that arbitrary precision is supported, so validation should not impose a particular fractional length.
Follow-up: What design concern follows from arbitrary precision? Downstream storage or serialization must define its own precision policy rather than relying on this schema to truncate input.
z.iso.date()z.iso.time()z.iso.duration()z.string()