function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
bohemianguy100bohemianguy100 

dynamic query - date variable format

I am using a dynamic query with two date variables.  The date variable is not in the correct format.  I did a system debug and the format is:

 

2011-02-26 00:00:00

 

How can I convert the date into the correct format to use in my dynamic query?

 

Here is my query:

 

strSOQL = 'select id,ownerId,subject,description,activitydate,activitydatetime,DurationInMinutes from Event where activitydate >= ' + da[0] + ' AND activityDate <= ' + da[1] + ' order by activitydatetime';

 

Thanks for any help.

Best Answer chosen by Admin (Salesforce Developers) 
Prajapati.LakhanPrajapati.Lakhan

You can try it out-

 

 

Date dt = System.today();
String dateStr = DateTime.newInstance(dt.year(),dt.month(),dt.day()).format('yyyy-MM-dd');

 

 

All Answers

Damien_Damien_

You should be able to do da[0].date and da[1].date or da[0].format() and da[1].format() but I'm not 100% sure.

 

Formatting details are in this link:

http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_methods_system_date.htm

bohemianguy100bohemianguy100

If I use da[0].format() it will format the date as: mm/dd/yyyy which causes the error System.QueryException: unexpected token: '/'

 

But, in a dynamic soql query the date format needs to be in the following format: yyyy-MM-dd

 

Surely there has to a be a way to simply format the date correctly.  I can even use the datetime format for the query if that is easier.

 

The date starts out like this: yyyy-MM-dd 00:00:00 and I need to end up with the correct date or datetime format for the dynamic query.

Prajapati.LakhanPrajapati.Lakhan

You can try it out-

 

 

Date dt = System.today();
String dateStr = DateTime.newInstance(dt.year(),dt.month(),dt.day()).format('yyyy-MM-dd');

 

 

This was selected as the best answer