Thursday, May 24, 2012
[You can see this blog for a more elegant solution ]
This was unknown to me and in past months I tried hard to use Datetime field in Dynamic SOQL query, well after doing lots of permutations and combinations I finally figured it out! which I though was not possible.
Well I guess this is worth sharing so here it is.
You can compare any Datetime field in Dynamic SOQL where query! Just keep in mind the format should be correct. You can use the format method to format datetime field like this where System.Now() is my Datetime field.
System.Now().format('yyyy-MM-dd\'T\'HH:mm:ss\'Z\''));
OR
DateTime dt = System.Now();//initialize datetime with current datetime
String formatedDt = dt.format('yyyy-MM-dd\'T\'HH:mm:ss\'Z\'');//format the datetime to make it Dynamic Soql ready
So a sample query to extract all the Accounts where the CreatedDate is less than Today will be
DateTime dt = System.Now();//initialize datetime with current datetime
String formatedDt = dt.format('yyyy-MM-dd\'T\'HH:mm:ss\'Z\'');//format the datetime to make it Dynamic Soql ready
Database.query('Select Id FROM Account WHERE CreatedDate<'+
formatedDt);