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:

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:

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