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\'');

    Update: 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);

    * I think, with the first method, you will lost the timezone info, ```JSON.serialize(dt).replace('"', '')``` can solve it. * with the second method, ```:dt``` must be in the same scope with ``Database.query(soql)``

    The answer here is almost correct. Specifying Z in the formatting string is essentially saying that it is formatted in Zulu. Thus the problem is two fold, one yo have to convert it to Zulu and second, the format hh will provide you with 12 hour. HH will provide you with military time (which is what Salesforce uses on the DB Level). Try this if you need to use dynamic SOQL for the date/time: DateTime dt =; String formattedDt = dt.format('yyyy-MM-dd\'T\'HH:mm:ss\'Z\'Zulu');

    Surely `formatGmt`?

License under CC-BY-SA with attribution

Content dated before 7/24/2021 11:53 AM