In some real time use cases, we need to convert datetime of one time zone to datetime of another timezone. This post will give different way of time conversion in another timezone.
Apex for converting time in different timezone
This TimeZoneService class will convert datetime of one timezone to another timezone. To convert timezone, we need correct TIMEZONESIDKEY. Here is complete list of supported timezone in salesforce. If we will use incorrect or not supported timezonesidkey, then we will get GMT timezone information.
Lets use above service class to convert time in different timezone.
1. Convert Datetime to another Timezone
We can convert any datetime value from one timezone to another timezone. Use above created TimeZoneService method to convert it.
DateTime dtTime=DateTime.now();
DateTime dtTimeTimeZone=new TimeZoneService() .convertDateTimeToOtherTimeZone(dtTime, 'America/Santiago','America/New_York');
2. Convert Time to another Timezone
Normally we save best time to call with timezone of patient, customer in salesforce record. If we have saved best time to call then we can use below code to convert into customer’s timezone. In below code acct.TimeToCall__c is account’s object field which need to be converted. Based on your requirement change field detail.
Date dt = Date.today();
Time tm=acct.TimeToCall__c;
DateTime dtTime=DateTime.newInstance(dt.year(),dt.month(),dt.day(),tm.hour(),tm.minute(),tm.second());
DateTime dtTimeTimeZone=new TimeZoneService().convertDateTimeToOtherTimeZone(dtTime, 'America/Santiago','America/New_York');
Reference:
https://help.salesforce.com/articleView?id=admin_supported_timezone.htm&type=0
4 comments
I can’t see TimeZoneService class code.
Hello Nithya,
It is already there Nithya.
Thank You,
Dhanik
Hi Dhanik, Very good article and very useful as well. but dont know i am not ale to find TimeZoneService in any salesforce help doc. can you please post link to the salesforce doc. unfortunately both examples are not getting executed and giving error “Invalid type: TimeZoneService”
Hello Raju,
TimeZoneService Code exists in the blog. Please click this https://salesforcecodex.com/salesforce/convert-datetime-of-one-timezone-to-datetime-of-another-timezone/ to get this post in non-mobile version. Looks like post directly opening in mobile version so might face that issue.
Thank You,
Dhanik