I have executed following code on developer console and it shows incorrect hour. Since the time used is from Seattle (Pacific time) which is 8 hours behind GMT. So when datetime.hourGMT() is used shouldn't the value be converted to GMT time and then the hour component should be fetched. Please advise if i am missing something or how is the calculation done.

Timezone tz = Timezone.getTimeZone('America/Los_Angeles');
DateTime SeattleTimeTest = DateTime.newInstance(System.Now().getTime() + tz.getOffset(System.Now()));
System.debug('Seattle Time ' +SeattleTimeTest+'-->'+SeattleTimeTest.hourGMT());


Seattle Time 2020-01-23 14:41:29-->14

1 Answer 1


Timezones are the bane of my existence, so I usually try to rationalize what is happening. Here is my result.

When you add your offset, apex will return a datetime record that will be identical to the time you have right now locally. However, as far as apex is concerned, that datetime will still be in GMT.

Hence, when you do hourGMT, you will get the exact hour you have in your datetime field. However, if you do hour, then apex will "translate" the time to your timezone.

In your case, System.debug('Seattle hour ' + SeattleTimeTest.hour()); will return 6, which would be Seattle local time when it is 14h in GMT.

The docs support this theory. For example, the docs for newInstance(milliseconds) say

Constructs a Datetime and initializes it to represent the specified number of milliseconds since January 1, 1970, 00:00:00 GMT.

You must log in to answer this question.

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