Loading

Date format 'YYYY' Is Not the Same as 'yyyy' in the Apex Datetime format() Method

게시 일자: Jun 19, 2026
상세 설명

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.

솔루션

Understanding the Difference Between 'YYYY'(Week Year) and 'yyyy' (Week of Year),

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.

Example

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

Summary of Results

  • 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.

Knowledge 기사 번호

000386309

 
로드 중
Salesforce Help | Article