The Date Problem
When you return aDate object in JSON, it’s automatically converted to an ISO 8601 string by calling toISOString():
z.date() schema doesn’t handle these conversions automatically.
The Solution: ez.dateIn() and ez.dateOut()
Express Zod API provides two custom schemas for handling dates:ez.dateIn()- For input: accepts ISO string, validates it, transforms toDateobjectez.dateOut()- For output: acceptsDateobject, transforms to ISO string for response
Using ez.dateIn()
ez.dateIn() accepts ISO date strings and transforms them into JavaScript Date objects:
Supported Date Formats
ez.dateIn() accepts several ISO 8601 date/time formats:
Using ez.dateOut()
ez.dateOut() accepts a Date object and transforms it to an ISO string for the response:
Complete Example
Here’s a real example from the Express Zod API source code:Adding Metadata
Bothez.dateIn() and ez.dateOut() accept metadata that appears in generated documentation:
Validation with Dates
You can add refinements to date schemas for additional validation:Common Date Patterns
Future Dates Only
Age Verification
Date Range
Implementation Details
Here’s howez.dateIn() works internally:
ez.dateOut():
Best Practices
Always Use ez.dateIn() for Input
Don’t use plain
z.date() for input schemas. It won’t handle JSON date strings correctly.Always Use ez.dateOut() for Output
Use
ez.dateOut() to ensure consistent ISO string formatting in responses.Store Dates as Date Objects
Work with proper Date objects in your handlers. Only convert to/from strings at API boundaries.
Include Examples
Add examples to help generate better API documentation and make your API easier to understand.
Troubleshooting
”Invalid date string” Error
Ensure the date string follows one of the supported ISO 8601 formats. Timestamps (epoch milliseconds) are not supported - convert them to ISO strings first:Timezone Issues
All dates are handled in ISO 8601 format, which includes timezone information. Be careful when comparing dates across different timezones.Next Steps
Pagination
Implement paginated endpoints
Transformations
Learn more about data transformations