3

How do we get user's time zone offset integer in Apex or Formula Field?

For example, a user's personal information time zone

(GMT-04:00) Eastern Daylight Time (America/New_York)

should return -4.


More information:

My requirement to have a commandButton Apex class which assigns custom object records to Users if the

custom object's state's time zone == the current user's time zone.

Hence, I created two fields on my custom object:

  1. State__c - for 2 letter USA state code
  2. GMT_Offset__c - formula field which maps all USA states to a time zone offset integer

However, I am unable to get the current user's time zone offset integer.

2 Answers 2

2

LaceySnr posted a solution to this problem on his blog a while back. AFAIK there have not been any timezone API changes since then that would render his solution obsolete.

Just beware - it's pretty rare to actually need the user's timezone offset, there is often a better way to achieve what you're trying to do either via VF or via non-offset-modified dates. If in doubt, post more info on what you're trying to achieve.

4
6

I'm late to the party, but in trying to tackle the same problem I arrived at the approach below for getting the exact value of the time zone offset. I hope this becomes useful if you ever face the same problem in the future (such as trying to render things correctly in Visualforce).

DateTime now = DateTime.now();
Long offset = DateTime.newInstance(now.date(), now.time()).getTime()
    - DateTime.newInstance(now.dateGmt(), now.timeGmt()).getTime();

System.debug('offset (milliseconds): ' + offset);
    // -14,400,000 for EDT (America/New_York)

System.debug('offset (hours): ' + (offset / (60 * 60 * 1000)));
    // -4 for EDT (America/New_York)
2
  • Can you explain how (offset / (60 * 60 * 1000) can convert gmt to -4GMT? What formula can I use to get +7 or +8 GMT?
    – compski
    Oct 13, 2017 at 16:47
  • 2
    Hi @compski the time zone offset is defined as the amount of time that must be added to the time expressed GMT to derive the local time. DateTime objects track time at the level of milliseconds, so by default the arithmetic gives back the offset in milliseconds. To convert from ms to hours, the math is offset in ms * (1 sec / 1000 ms) * (1 min / 60 sec) * (1 hr / 60 min).
    – Marty C.
    Oct 18, 2017 at 22:55

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .