Print this page

Using YYYY is NOT the same as yyyy with format() function

Knowledge Article Number 000206852
Description Formatting using YYYY is NOT the same as yyyy when using format() function of Datetime Class.
Resolution Run the below snippet of code: 

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')); 

You will notice that while doing the format (myDateTime.format('MM/dd/YYYY h:mm a')), it is increasing the year from 2014 to 2015.
This happens only from days 28 to 31 for December. 

Now for format (myDateTime.format('MM/dd/yyyy h:mm a')) , date will not change.

Formatting using YYYY is NOT the same as yyyy. 

Formatting using the YYYY notation would result in returning the "week year". 

Here is the explanation from the documentation: 

Week Of Year and Week Year 

Values calculated for the WEEK_OF_YEAR field range from 1 to 53. The first week of a calendar year is the earliest seven day period starting on getFirstDayOfWeek() that contains at least getMinimalDaysInFirstWeek() days from that year. It thus depends on the values of getMinimalDaysInFirstWeek(), getFirstDayOfWeek(), and the day of the week of January 1. Weeks between week 1 of one year and week 1 of the following year (exclusive) are numbered sequentially from 2 to 52 or 53 (except for year(s) involved in the Julian-Gregorian transition). 

The getFirstDayOfWeek() and getMinimalDaysInFirstWeek() values are initialized using locale-dependent resources when constructing a GregorianCalendar. The week determination is compatible with the ISO 8601 standard when getFirstDayOfWeek() is MONDAY and getMinimalDaysInFirstWeek() is 4, which values are used in locales where the standard is preferred. These values can explicitly be set by calling setFirstDayOfWeek() and setMinimalDaysInFirstWeek(). 

A week year is in sync with a WEEK_OF_YEAR cycle. All weeks between the first and last weeks (inclusive) have the same week year value. Therefore, the first and last days of a week year may have different calendar year values. 

For example, January 1, 1998 is a Thursday. If getFirstDayOfWeek() is MONDAY and getMinimalDaysInFirstWeek() is 4 (ISO 8601 standard compatible setting), then week 1 of 1998 starts on December 29, 1997, and ends on January 4, 1998. The week year is 1998 for the last three days of calendar year 1997. If, however, getFirstDayOfWeek() is SUNDAY, then week 1 of 1998 starts on January 4, 1998, and ends on January 10, 1998; the first three days of 1998 then are part of week 53 of 1997 and their week year is 1997. 

References :

promote demote