+ Start a Discussion
craigmhcraigmh 

Date field is cast as string with time from dynamic SOQL

Here is my code:

 

sObject obj = database.query('Select DateField__c From OpportunitySchedule__c Where Id = \'' + string.escapeSingleQuotes(objId) + '\' Limit 1');
date dtSelectedDate = date.valueOf(obj.get('DateField__c'));

 

 DateField__c is of datatype date, not datetime.

 

When I try to run this code, this is the error that I get:

Invalid date: 2011-06-25 00:00:00

 

When I try to cast it as a datetime, this is the error that I get:

Invalid date/time: 2011-06-25 00:00:00

 

When the date is cast as a string, is it converted to a format that is impossible to get back to a date or date/time by any method other than manual parsing?

 

FYI, here's my hack fix, after the query:

 

string strDate = string.valueOf(obj.get('DateField__c'));
strDate = strDate.substring(0, strDate.indexOf(' '));
date dtSelectedDate = date.valueOf(strDate);

 

IspitaIspita

Good fix .... Thankx for sharing it.............

 

mikefitzmikefitz

try using just .format() as in 

 

date dtSelectedDate = date.valueOf(obj.get('DateField__c')).format();

 

That should remove the 00:00 from your date.

 

Good luck!

craigmhcraigmh

Mike,

 

The format() method returns a string, so I get this error when trying to save the class:

Error: Compile Error: Illegal assignment from String to Date

 

Although I may try to play around with that a bit more.

crop1645crop1645

craigmh:

 

I think your issue is that if you use system.debug to print a date (or otherwise expose a date to print as a string, APEX will format it with a default time of 00:00:00.

 

I replicated your code in my environment using my own date field as shown below:

Account a = new Account(name = 'foo', support_start_date__c = Date.newInstance(2011,6,25));
insert a;

sObject obj = database.query('Select support_start_date__c From Account Where Id = \'' + string.escapeSingleQuotes(a.id) + '\' Limit 1');
Date dtSelectedDate = Date.valueOf(obj.get('Support_Start_date__c'));
System.debug(loggingLevel.INFO,'RESULT dtSelectedDate=' + dtSelectedDate);

Boolean areDatesTheSame = dtSelectedDate == Date.newInstance(2011,6,25);
System.debug(loggingLevel.INFO,'RESULT are dates the same: ' + areDatesTheSame);

 and did Anonymous Apex execute getting these results:

 

16:55:36.192 (192121000)|SOQL_EXECUTE_BEGIN|[4]|Aggregations:0|Select support_start_date__c From Account Where Id = '001V00000057gaHIAQ' Limit 1
16:55:36.196 (196091000)|SOQL_EXECUTE_END|[4]|Rows:1
16:55:36.196 (196403000)|USER_DEBUG|[6]|INFO|RESULT dtSelectedDate=2011-06-25 00:00:00
16:55:36.196 (196538000)|USER_DEBUG|[9]|INFO|RESULT are dates the same: true