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?

Answer

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

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

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

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

Leave a Comment