Time Zone Conversion in Salesforce

|
| By Webner

Problem: How to change the Time Zone in VF Pages of Salesforce to show the Date Time field according to User’s Time Zone?

Solution:

By default the Date Time field is saved in GMT TimeZone. If you simply use the System.now() method in order to fetch the current Date Time then it will give Date Time in GMT time zone format.

Code:

Datetime dateTimeInGMT=System.now();
System.debug('Datetime in GMT TimeZone : '+dateTimeInGMT);

Output:
Datetime in GMT TimeZone : 2018-03-26 06:44:42

To change the Time Zone of the Date Time field in VF Pages of Salesforce to the User’s Time Zone firstly, fetch the user’s time zone using UserInfo.getTimeZone().getID(). After that just convert the Date Time in that format.

Code:

String userTimeZone = UserInfo.getTimeZone().getID();
Datetime dateTimeInGMT=System.now();
String stringDate1=dateTimeInGMT.format('MM/dd/yyyy HH:mm a',userTimeZone);
System.debug('Datetime data in User’s Timezone : '+stringDate1);

Output:
Datetime data in User’s Timezone : 3/26/2018 1:40 AM

Leave a Reply

Your email address will not be published. Required fields are marked *