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

7

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

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .