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
si risi ri 

how convert a string into Datetime format in apex

Hi all, how convert a string into Datetime format in apex?
String starttime = '2018-12-29T15:30:00+05:30';
DateTime  dt = DateTime.valueof(starttime );
system.debug('dt value :' +dt ); 
dt = 2018-12-29 10:00:00
so now I want to convert (dt = 2018-12-29 10:00:00) equals to 
2018-12-29T10:00:00.000+0000 format. how I can convert this please guide me.
Team NubesEliteTeam NubesElite
Hi,
I think you have an issue with the hyphens used instead of slashes, if you fix that, the DateTime.parse method will consume your string without issue. Note that the format will be dependent on the user (dd/mm/yyyy vs mm/dd/yyyy) I referenced this during testing Datetime format ignores am/pm? the below code compiles fine.
String testDateString = '11-11-2014 08:00 AM'.replace('-','/');
DateTime testDate = DateTime.parse(testDateString);
String convertedDate = testDate.formatGmt('yyyy-MM-dd\'T\'HH:mm:ss\'Z\'');
System.debug('xxx'+convertedDate);
After you have the datetime in the second line, you can do the comparison you require.



Thank You
www.nubeselite.com

Developement | Training | Consulting

Please mark this as solution if your problem resolved.
Ajay K DubediAjay K Dubedi
Hi,

Use the below code get the solution:

String val = '2018-12-29T15:30:00+05:30'; 
DateTime date1 = (DateTime)Json.deserialize('"'+val+'"', DateTime.class);
System.debug(date1);// 2018-12-29 10:00:00
String convertedDate = date1.formatGmt('yyyy-MM-dd\'T\'hh:mm:ss\'Z\'');
system.debug(convertedDate);

I hope you find the above solution helpful. If it does, please mark as Best Answer to help others too.

Thanks and Regards,
Ajay Dubedi
www.ajaydubedi.com