Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can zod date type accept ISO date strings?

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()
like image 652
birgersp Avatar asked Sep 01 '25 06:09

birgersp


1 Answers

I used this from the README which works since v3.20 https://github.com/colinhacks/zod#dates

In your code snippet it would turn into this:

import { z } from "zod"

const someTypeSchema = z.object({
    t: z.coerce.date(),
})
type SomeType = z.infer<typeof someTypeSchema>
like image 151
qimolin Avatar answered Sep 02 '25 22:09

qimolin