How to sort by date without time in Sanity dateTime fields?
You don't need to add a new field or migrate your 3000+ documents! You can handle date-only sorting directly in your GROQ queries, though the approach is a bit different than you might expect.
The Core Challenge
dateTime fields in Sanity store ISO 8601 strings like 2024-01-15T14:30:00Z. When you sort by these fields directly, posts published on the same day will be ordered by their exact time, which can cause inconsistent ordering when combined with other sort criteria.
Solution: Sort by the Full DateTime Field
The most straightforward approach is to use the dateTime() function to ensure proper chronological sorting:
*[_type == "post"] | order(dateTime(publishedAt) desc)For multiple field sorting while maintaining date order:
*[_type == "post"]
| order(category asc, dateTime(publishedAt) desc)This sorts by category first, then by full datetime within each category. Posts published on the same day will maintain a consistent order based on their publication time.
If You Truly Need Date-Only Sorting
GROQ doesn't have built-in functions to extract just the date portion from a datetime field. However, since ISO 8601 datetime strings start with the date in YYYY-MM-DD format, you have a couple options:
Option 1: Use the datetime as-is - In most cases, sorting by the full datetime is actually desirable because it provides consistent, deterministic ordering. Posts from the same day will always appear in the same order.
Option 2: Add a date-only field - If you genuinely need date-only sorting (where posts from the same day should be treated as equal for sorting purposes), adding a separate date field is the cleanest approach. You could use a Sanity Function to automatically populate this field whenever a document is created or updated, avoiding manual migration.
Multi-Field Sorting
The order() function supports multiple sort expressions separated by commas. The order matters - later expressions only affect ordering when earlier ones are equal:
*[_type == "post"]
| order(
featured desc,
category asc,
dateTime(publishedAt) desc
)This would show featured posts first, then sort by category, then by publication date within each category.
Why Not String Manipulation?
While you might think to extract just the date portion using string operations, GROQ has limited string manipulation functions available. The datetime approach is the officially supported method for working with temporal data in queries.
Hope this helps clarify your options! The dateTime() function approach should work well for most use cases without requiring any schema changes.
Show original thread10 replies
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.