When using the Apex Datetime.format() method, the date format pattern 'YYYY' (Week Year) and 'yyyy' (Calendar Year) produce different results. This difference is most noticeable for dates in the last week of December, where 'YYYY' may return a year value one higher than expected.
The Apex Datetime.format() method uses the Java SimpleDateFormat standard:
'yyyy' returns the calendar year — the actual year of the date.'YYYY' returns the week year — the year that contains the majority of the ISO week in which the date falls. For dates in the last week of December, this can be the following calendar year.The following Apex code creates a DateTime of December 28, 2014 and formats it using both patterns. Running this in the Developer Console demonstrates the difference:
Datetime myDateTime = Datetime.newInstance(2014, 12, 28);
system.debug('datetime::' + myDateTime);
system.debug('datetime::' + myDateTime.format('MM/dd/YYYY h:mm a'));
system.debug('datetime::' + myDateTime.format('MM/dd/yyyy h:mm a'));
myDateTime.format('MM/dd/YYYY h:mm a') returns 2015 for dates from December 28–31, 2014. This is the "week year" — YYYY notation returns the week year.myDateTime.format('MM/dd/yyyy h:mm a') always returns 2014 for a date in 2014. The year does not change.Recommendation: Use 'yyyy' (lowercase) in all Apex date format strings unless you specifically intend to use week year semantics.
000386309

We use three kinds of cookies on our websites: required, functional, and advertising. You can choose whether functional and advertising cookies apply. Click on the different cookie categories to find out more about each category and to change the default settings.
Privacy Statement
Required cookies are necessary for basic website functionality. Some examples include: session cookies needed to transmit the website, authentication cookies, and security cookies.
Functional cookies enhance functions, performance, and services on the website. Some examples include: cookies used to analyze site traffic, cookies used for market research, and cookies used to display advertising that is not directed to a particular individual.
Advertising cookies track activity across websites in order to understand a viewer’s interests, and direct them specific marketing. Some examples include: cookies used for remarketing, or interest-based advertising.