How to Convert TimeZone Values in Salesforce?

In Salesforce, converting the timezone values is required when working with users and customers from different time zones.

With this, we can efficiently handle time-related tasks, such as scheduling meetings, tasks, and deadlines, depending on proper timezone settings.

In this Salesforce tutorial, we will learn how to convert TimeZones in Salesforce Apex. Additionally, I will explain how to convert the time zone values in Salesforce SOQL queries.

Convert Timezone values in Salesforce

In Salesforce, we can use different approaches, such as built-in DateTime functions and the convertTimezone() function, which can help automate the time zone conversion process.

The DateTime function converts data stored in one timezone into another based on the user’s profile settings. Meanwhile, the convertTimezone() function takes a specific date and time and adjusts it based on the user’s local time zone.

Timezone Conversion using TimeZone and DateTime in Salesforce Apex

In the steps below, we will demonstrate the basic conversion of timezone values using the DateTime and TimeZone functions.

Let’s take a scenario where we have to convert the original DateTime in GMT timezone, for that, we can use the below apex code.

DateTime originalDateTime = DateTime.now();
System.debug('Original DateTime (GMT): ' + originalDateTime);

In the above code, I have used the DateTime.now(), and fetched the value for the current time in the GMT timezone.

Output:

How to convert timezone in Salesforce Apex

This way, we can convert the current datetime value to the GMT timezone in Salesforce Apex using the above code.

When you have to convert the time zone into any specific region time zone, like the USA Los Angeles, then we can use the below apex code:

DateTime originalDateTime = DateTime.now();
TimeZone tz = TimeZone.getTimeZone('America/Los_Angeles');
DateTime convertedDateTime = originalDateTime.addSeconds(tz.getOffset(originalDateTime) / 1000);
System.debug('Converted DateTime (America/Los_Angeles): ' + convertedDateTime);

In the above code, the DateTime.now() shows UTC, and TimeZone tz = TimeZone.getTimeZone(‘America/Los_Angeles’) retrieves the time zone for a specific region.

Output:

Convert timezone values in Salesforce Apex

Using the above method, we can convert the value for any specific time zone in Salesforce Apex. In the above code, I have the DateTime.now() for the current date time, and you can use another date time field to convert its value into any specific time zone.

Salesforce SOQL Converting Time Zones in Date Functions

In Salesforce, SOQL queries return datetime field values in UTC. Using the convertTimezone() function, we can convert the datetime field values to user time.

When we use the convertTimezone() in the SOQL queries, we need to use it with the Date function; otherwise, it will return the error “Invalid aggregate function: convertTimezone.”

For example, the below SOQL query will return an error because there is no Date function.

SELECT convertTimezone(CreatedDate), SUM(Amount) 
FROM Opportunity 
GROUP BY convertTimezone(CreatedDate)

Returned Error:

Invalid aggregate function convertTimezone in Salesforce

Now, to avoid the error, we will use the date functionDAY_ONLY.” This will fetch and return the day(date) part from the date-time field. The other fields referred to in the SELECT clause should be grouped similarly to how we grouped the currency field ‘Amount’ with the aggregate function ‘SUM’.

SELECT DAY_ONLY(convertTimezone(CreatedDate)), SUM(Amount) 
FROM Opportunity 
GROUP BY DAY_ONLY(convertTimezone(CreatedDate))

Output:

Convert timezone into date values in Salesforce SOQL

Instead of a day, if you want to fetch the hour from the datetime field according to the user’s timezone, then we can use the Date function “HOUR_IN_DAY.”

SELECT HOUR_IN_DAY(convertTimezone(CreatedDate)), SUM(Amount) 
FROM Opportunity 
GROUP BY HOUR_IN_DAY(convertTimezone(CreatedDate))

Output:

Convert Date time fields to User timezone in Salesforce SOQL

This way, we can convert the Time Zones to date and time values in SOQL according to the user’s timezone.

Timezone Conversion in Salesforce Apex using the Custom Function

In Salesforce, we can create a custom function to handle the timezone conversions based on specific business logic.

1. Create a public Apex class and enter the code below to define the logic for timezone conversion.

public class TimeZoneConverter {
    public static DateTime convertTimeZone(DateTime dt, String fromTimeZoneId, String toTimeZoneId) {
        TimeZone fromTimeZone = TimeZone.getTimeZone(fromTimeZoneId);
        TimeZone toTimeZone = TimeZone.getTimeZone(toTimeZoneId);
        Integer offsetFrom = fromTimeZone.getOffset(dt) / 1000;
        Integer offsetTo = toTimeZone.getOffset(dt) / 1000;
  
        DateTime adjustedDateTime = dt.addSeconds(offsetTo - offsetFrom);
        return adjustedDateTime;
    }
}

In the above class method, the convertTimeZone method converts a given DateTime object from one time zone to another, and then it retrieves the offsets for both the source and target time zones for the given date and time.

The offsets are calculated in seconds by dividing the result of getOffset() by 1000.
Then, the method adjusts the input DateTime by adding the difference between the target and source time zone offsets.

2. Now, call the class method in the Apex anonymous window to check its functionality using the code below.

DateTime gmtDateTime = DateTime.now(); 
DateTime pstDateTime = TimeZoneConverter.convertTimeZone(gmtDateTime, 'GMT', 'America/Los_Angeles');
System.debug('Converted DateTime to PST: ' + pstDateTime);

Output:

Get Timezone converted value in Salesforce

Using the above method, we can manipulate the time zone by converting and displaying the time for different users and regions.

Conclusion

In this Salesforce tutorial, we have learned about getting the converted values of timezones for specific regions and also according to the user’s timezone. In the above methods, we have used the function DateTime and convertTimezone() to convert the time zones according to the scenario.

Using the above query methods, we also learned how to fetch the converted timezone values in date functions for user timezone in Salesforce SOQL queries.

You may also like to read:

Agentforce in Salesforce

DOWNLOAD FREE AGENTFORCE EBOOK

Start with AgentForce in Salesforce. Create your first agent and deploy to your Salesforce Org.

Salesforce flows complete guide

FREE SALESFORCE FLOW EBOOK

Learn how to work with flows in Salesforce with 5 different real time examples.