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.
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:
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.