Does the `dateTime()` Function in GROQ Require the `Datetime` or `Date` Data Types?

3 replies
Last updated: Sep 29, 2022
does anyone know if the
dateTime()
function in GROQ requires the
Datetime
data type, or can it be used with just the
Date
type? I’m getting a null response trying to run the following query
*[_type == "exhibition"]{ "dateTIme": dateTime(startDate) }
where startDate is a
Date
type.
I’m trying to compare two
date
in order to return a specific document within a certain range of dates
AI Update

The dateTime() function in GROQ expects a datetime string in RFC3339 format (like 1985-04-12T23:20:50.52Z), which is why you're getting null when using it with a Date type field.

The issue is that Sanity's Date type stores only the date portion (like 2024-01-15) without the time component, so dateTime() can't parse it directly.

The fix: Concatenate a time string to your date field to make it RFC3339 compatible:

*[_type == "exhibition"]{
  "dateTime": dateTime(startDate + 'T00:00:00Z')
}

This appends midnight UTC to your date, converting it into a format that dateTime() can parse.

For comparing dates in a range:

You can use this approach to filter exhibitions within a date range:

*[_type == "exhibition" 
  && dateTime(startDate + 'T00:00:00Z') >= dateTime("2024-01-01T00:00:00Z")
  && dateTime(startDate + 'T00:00:00Z') <= dateTime("2024-12-31T23:59:59Z")
]

Alternative approach: If you're just comparing dates (not times), you might not even need dateTime() at all. Simple string comparison works for date fields since they're stored in ISO format:

*[_type == "exhibition" 
  && startDate >= "2024-01-01"
  && startDate <= "2024-12-31"
]

This is cleaner and works perfectly fine for date-only comparisons. Save dateTime() for when you actually need datetime precision with time components.

The GROQ functions documentation has more details on how dateTime() works with different input formats.

It looks like
dateTime
only accepts RFC3339 format strings like:
1985-04-12T23:20:50.52Z
. I was able to get it to work if I did this though:
dateTime(<date-field> + 'T00:00:00Z')
user M
ty! I forgot you could use strings in groq like that!
There's so much GROQ can do that it's easy to forget stuff 😅

Sanity – Build the way you think, not the way your CMS thinks

Sanity is the developer-first content operating system that gives you complete control. Schema-as-code, GROQ queries, and real-time APIs mean no more workarounds or waiting for deployments. Free to start, scale as you grow.

Was this answer helpful?