15

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?

edgartheunready
  • 2,935
  • 7
  • 23
  • 38

2 Answers2

19
    Datetime dt = Datetime.now();
    String formattedDt = dt.formatGmt('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);
Benjamin Luehrs
  • 473
  • 4
  • 14
edgartheunready
  • 2,935
  • 7
  • 23
  • 38
  • 1
  • 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)

  • – Hao Liu May 08 '15 at 07:09
  • 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 = System.now(); String formattedDt = dt.format('yyyy-MM-dd'T'HH:mm:ss'Z'Zulu'); – Jason Hardy May 31 '16 at 23:02
  • 1
    Surely formatGmt? – Keith C Sep 12 '19 at 09:31