3

I have a requirement to convert string value to DateTime without converting it to time zone. Ex:

Datetime today = Datetime.now(); 
String myDate = today.format('yyyy-MM-dd HH:mm:ss');
Datetime myDateTime = Datetime.valueOf(myDate);

System.debug('myDate:: '+myDate );  
System.debug('myDateTime:: '+myDateTime); 

in the above example, if myDate is 2019-09-15 23:03:23 then myDateTime is appearing as 2019-09-15 17:33:23 by converting to different time zone.

I want to get same value for both myDate and myDateTime.

Is there any way to do that?

1 Answer 1

5

Datetime Documentation is actually confusing.

Note:

valueOf: Returns the datetime in GMT timezone
valueOfGmt: Returns the datetime relative to GMT timezone

So, change the code to below:

Datetime today = Datetime.now(); 
String myDate = today.format('yyyy-MM-dd HH:mm:ss');
Datetime myDateTime = Datetime.valueOfGmt(myDate);

System.debug('myDate:: '+myDate );  
System.debug('myDateTime:: '+myDateTime); 
1
  • 1
    It worked! Thanks
    – Arzad
    Sep 17, 2019 at 5:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.