How to write SOQL queries with dates

Anw how to remember the format in the future

Posted by Martin Haagen on Thursday, May 4, 2023

How to write SOQL queries with dates

Date formats and SOQL may be super straightforward. But if you work with multiple languages, it may be hard to remember how you use dates and times in SOQL queries.

TL;DR;

Format: YYYY-MM-DDTHH:MM:SSZ

Example: 2023-05-04T12:02:23Z

There is a quick way to get to the format if you forget it. You can, in your developer instance, open the developer console and write the following piece of “anonymous apex” (check the “Open Logs” box before hitting “Execute”).

DateTime dt = DateTime.now();
System.debug(dt);

When you examine your debug log, you will find something that looks like this:

Output from the Debug logs showing the correct date format

An example SOQL query could look like this:

SELECT Id FROM Account WHERE CreatedDate > 2023-01-01T00:00:00Z

You should not use single or double quotes writing the date string. The Developer Console is a tool to experiment with writing SOQL queries.

Knowing the date format is handy when exporting a dataset based on fixed dates with the dataloader. It can also be helpful when writing queries via the APIs.

Happy coding!