Blog

Date Time and Timezone Handling in Apex

I recently had to do some work converting timezones in Apex. Unfortunately, Apex is missing some key conversion functionality when it comes to handling times. I created this class to handle figuring out the time-offset of the current user (hardcoded to Eastern Time) and then use that to convert a time in another timezone. It also has a couple of handy methods for retrieving DST start/end dates and getting a list of US timezones with GMT offset.

Hopefully someone else out there will find this useful if they need to handle datetime conversions in their Apex code.

You’re correct, this Apex would pull the time zone of the Guest Salesforce user. You’d have to use JavaScript to get the timezone of the visitors local machine and find a way to do some coding either in JS, or pass the time zone back to Apex to use in that same class.

Best Regards,

Mike

Sachin Mittal
on 23 July 2012 at 1:53 am

Hi Michael,
I have a query on the public Map getTZSidKeys() function you have developed.
What is the use of creating a map like this if we could create a list of user record having the TimeZoneSidKey values.
Also what is the values we are passing in the integer part of the map and how to change it if we want:
tzSIDKeys.put(‘America/Adak’, new Integer[]{-10, -9});

Sachin Mittal
on 23 July 2012 at 1:56 am

I am writing s trigger to set the reminder time for a task by adding the due date time to the assigned user timezone offset.
How to achieve this

It’s been a couple of years since I wrote this, but from what I remember the map created in getTZSidKeys() returns DST and non-DST offsets. This isn’t available on the User object, even if you pull the picklist values in the TimeZoneSidKey field.

Best Regards,

Mike

Hardik
on 26 June 2013 at 5:38 am

Hi
Thanx for sharing this code.
This code is only base on US DST time zone.
If I want to calculate DST for all GMT timezone then how to do that?

Can I get list of all DST start and end date according to GMT timezone?
Please reply me as soon as possible