1

In below execute anonymous code I am seeing a strange behaviour.

DateTime myDateTime = DateTime.newInstanceGMT(2019, 12, 30, 0, 0, 0);
system.debug('myDateTime === ' + myDateTime);
DateTime newDateTime = myDateTime.addHours(16);
system.debug('newDateTime === ' + newDateTime.format('YYYY-MM-dd HH:mm:ss', 'America/Phoenix'));

enter image description here

I see the year changes from 2019 to 2020 , which is unexpected. Is there anyway I could have 2019 instead of 2020 here?

1

Your last format should use yyyy and not YYYY

system.debug('newDateTime === ' + newDateTime.format('yyyy-MM-dd HH:mm:ss', 'America/Phoenix'));

correctly returns 2019-12-30 09:00:00

Frankly, not sure why YYYY fails while yyyy works, since I can't find documentation that uses the uppercase version at all.

==Update==

I found it. Per this doc, YYYY refers to "Week Year" and that week, if you look here, would correctly be in 2020.

So that's the answer.

| improve this answer | |
  • 1
    Nice catch! That's strange that YYYY is different from yyyy – SfdcBat Dec 24 '19 at 18:59

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.