+ Start a Discussion
NaveenReddyNaveenReddy 

How convert String to DateTime in apex?

Hi,
Can any one help me in converting String to DateTime in apex.
Im able convert below format.

DateTime dt = DateTime.parse('11/6/2014 12:00 AM');

If I use below format Im getting error.

Datetime dt = DateTime.formatGmt('09-Dec-2014 10:43 AM');

System.TypeException: Invalid date/time: 09-Dec-2014 10:43 AM.

Thanks in advacne.

Regards,
naveen.


 
NaveenReddyNaveenReddy
Small correction.

Datetime dt = DateTime.parse('09-Dec-2014 10:43 AM');
Evan KennedyEvan Kennedy
I believe the parse is looking for dates in a particular format, the UTC one, if I'm not mistaken. So it won't understand a datetime that's in a different format.

http://www.w3.org/TR/NOTE-datetime
M.sfM.sf
strDt = '1/25/2018';
//convert String to Date(output:2018-01-25 00:00:00)
Date dt = Date.parse(strDt);
//convert date to DateTime.Can be used in soql but not in dynamic soql(output:2018-01-25 05:00:00)
DateTime dtAndTime = DateTime.newInstance(dt.year(),dt.month(),dt.day(),0,0,0);
//if using in dynamic soql convert dateandtime to string(output:2018-01-23T05:00:00Z).
String startDateQuery = startDate.formatGMT('yyyy-MM-dd\'T\'hh:mm:ss\'Z\'');
 
Asif SheikhAsif Sheikh
Hi, 
Try System.debug(DateTime.parse('11/23/2020, 11:23 AM'));