How is a DateTime object formatted into a String suitable for a String based SOQL query?

In order to write a where clause against a datetime field, you need to format your dateTime object into the following format:

WHERE SystemModstamp > 2005-10-08T01:02:03Z

How do you correctly convert the dateTime object to a String?


    DateTime dt =;
    String formattedDt = dt.format('yyyy-MM-dd\'T\'hh:mm:ss\'Z\'');

Another option is to use SOQL dynamic binding, no formatting required.

    DateTime dt =;
    String query = 'SELECT Id FROM User WHERE  SystemModstamp > :dt '
    List<SObject> results = Database.query(query);

Source : Link , Question Author : edgartheunready , Answer Author : edgartheunready

Leave a Comment