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?
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 = 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);
Just use datetime variable in the SOQL where clause.
For example:
Datetime dt = DateTime.newInstance(2005,10,8,01,02,03);
List<Account> accounts = [SELECT Id, Name FROM Account WHERE CreatedDate < :dt];
System.debug(accounts.size());
I have been using string based queries because I generate the list of all columns at runtime. Is there a way to do that using the [SELECT ...] syntax? (that should probably be a separate SE question)
– edgartheunready Jan 29 '14 at 17:05
I think, with the first method, you will lost the timezone info,
JSON.serialize(dt).replace('"', '')can solve it.with the second method,
:dtmust be in the same scope withDatabase.query(soql)formatGmt? – Keith C Sep 12 '19 at 09:31