3

My user's timezone is GMT+2 (Eastern European Time) and I notice strange thing when playing around with dates.

Date myDate = Date.newInstance(2019, 11, 29);
Time myTime = Time.newInstance(9,0,0,0);

System.debug(Datetime.newInstance(myDate, myTime));
System.debug(Datetime.newInstanceGmt(myDate, myTime));

I am creating Datetime instance from 9 hour. I expect Datetime.newInstance to return Datetime with 9 o'clock. And for newInstanceGmt I expect it to be 7 o'clock, because when in my timezone it's 9, in London it's 7 am.

But the result I get is the following:

09:44:51.11 (12596972)|USER_DEBUG|[4]|DEBUG|2019-11-29 07:00:00
09:44:51.11 (12638407)|USER_DEBUG|[5]|DEBUG|2019-11-29 09:00:00

It's flipped over. For some reason Salesforce is instantiating newInstance with subtracting my timezone offset, which is not logical to me.

2

System.debug(dateTimeVariable) always outputs a DateTime value in GMT. What you're looking at is 7:00:00 AM GMT and 9:00:00 AM GMT, respectively. To get the results you expect, use format() instead.

Date myDate = Date.newInstance(2019, 11, 29);
Time myTime = Time.newInstance(9,0,0,0);

System.debug(Datetime.newInstance(myDate, myTime).format());
System.debug(Datetime.newInstanceGmt(myDate, myTime).format());
1
  • Oh that makes a difference, thanks for help! – Vladyslav K Nov 29 '19 at 8:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.