When defining a schema with zod, how do I use a date type?
If I use z.date()
(see below) the date object is serialized to a ISO date string. But then if I try to parse it back with zod, the validator fails because a string is not a date.
import { z } from "zod"
const someTypeSchema = z.object({
t: z.date(),
})
type SomeType = z.infer<typeof someTypeSchema>
function main() {
const obj1: SomeType = {
t: new Date(),
}
const stringified = JSON.stringify(obj1)
console.log(stringified)
const parsed = JSON.parse(stringified)
const validated = someTypeSchema.parse(parsed) // <- Throws error! "Expected date, received string"
console.log(validated.t)
}
main()
z.string().datetime()
to work for me: github.com/colinhacks/zod#iso-datetimes – Wick