The purpose of this article is to explain different methods of timezone classes, and how they can be used. Even though Salesforce used to convert the dates based on the logged-in user timezone, however, you wanted to see a time to a different timezone, you can do it with the TimeZone class.
You can use below methods to calculate time in different time zones.
TimeZone Methods:
- getDisplayName() - Returns this time zone’s display name.
- getID() -Returns this time zone’s ID.
- getOffset(date) -Returns the time zone offset, in milliseconds, of the specified date to the GMT time zone.
- getTimeZone(timeZoneIdString) -Returns the time zone corresponding to the specified time zone ID.
- toString() -Returns the string representation of this time zone.
In the above methods, getOffset() method is very important. An offset is the number of hours or minutes a certain time zone is ahead of or behind GMT. A time zone’s offset can change throughout the year because of Daylight Saving Time.
User Case
Let’s say, there is a sales Rep, who calls customers and book appointments with experts to assist their needs. Suppose the Sales Rep is sitting in Dallas which is in Central time-zone and he called to a customer who is sitting in (New York Eastern time zone). While booking the appointment, the customer will suggest time as per his local time zone. In that case, sales Rep needs to convert time to his timezone. So if a user suggests 12 PM EST, it will be 11 AM CST. Using the below logic, sales rep no need to worry about this conversion.
public static DateTime getConvertedTime(DateTime anyDateTime, string sourceTimezoneId, string targetTimezoneId){
//get source time-zone corresponding to the specified time zone ID
TimeZone sourceTimeZone = Timezone.getTimeZone(sourceTimezoneId);
//get source time-zone offset in milliseconds
Integer sourceGMT_Time=sourceTimeZone.getOffset(anyDateTime);
//get Target time-zone corresponding to the specified time zone ID
TimeZone targetTimeZone = Timezone.getTimeZone(targetTimezoneId);
//get target time-zone offset in milliseconds
integer targetGMT_Time = targetTimeZone.getOffset(anyDateTime);
//Get the difference in milliseconds
Integer differenceInMs = targetGMT_Time- sourceGMT_Time;
//Convert difference into minutes
Integer differenceInSec= differenceInMs/1000;
//Add difference to the time, to get time in target timezone
DateTime timeInTargetTimeZone = anyDateTime.addMinutes(differenceInSec);
return timeInTargetTimeZone;
}
Reference: Salesforce Documentation