We noticed a behavior with formatGmt function especially around using YYYY vs yyyy, anyone facing the same?

Below is showing one year ahead:

system.debug('GMT Time'+System.now().formatGmt('E, dd MMM YYYY HH:mm:ss z'));

The above code worked perfectly till last week, starting today or over the weekend above code started to return 2021 for YYYY, when we replaced YYYY to yyyy (ie below code) it's returning 2020 ie showing current year 

system.debug('GMT Time'+System.now().formatGmt('E, dd MMM yyyy HH:mm:ss z'));
  • Exactly, I'm facing the same issue. It's very weird, confusing and not documented anywhere in Salesforce. Please help! Dec 28 '20 at 11:14

YYYY is week based calendar.

yyyy is our ordinary calender.

This is not SF behavior. but something expected whenever you use yyyy or YYYY as they are derived from java SimpleDateFormat.

Even SF document points to refer SimpleDateFormat.

Here is an excellent blog post showing this behaviour.

  • Thanks, Pranay, we figured it out the moment we posted the question. Appreciate your prompt answer though. Dec 28 '20 at 11:29

Got the answer

  • y return year of the era
  • Y returns week year

so in this last week of Dec when a/few day(s) of the week is/are of next year, YYYY will return 2021 (ie week year) and yyyy (as always) will return current year ie 2020.

In short, if you are looking for the current year always use yyyy and not YYYY else these dec boundary weeks will trouble you; as it did to me.

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.