YYYY vs yyyy in Salesforce Apex: Understanding the Critical Date Formatting Difference
The article clarifies the critical difference between the date formatting patterns 'yyyy' and 'YYYY' in Salesforce Apex. While 'yyyy' represents the standard calendar year, 'YYYY' corresponds to the ISO week-based year, which can cause incorrect year values around year-end dates. Understanding this distinction helps Salesforce developers prevent subtle bugs in integrations, automation, and reports that rely on accurate year formatting. Using 'yyyy' by default is advised unless ISO week-based year calculations are specifically required.
- Use 'yyyy' for standard calendar year formatting in Apex Date and Datetime.
- Avoid 'YYYY' unless working with ISO week-based year requirements.
- Beware of incorrect year values in documents, integrations, and reports at year-end.
- Understand that 'YYYY' reflects the ISO week-based year starting on Monday.
- Adopt best practice to prevent subtle year formatting bugs in Salesforce automation.
When working with date formatting in Salesforce Apex, developers often rely on formatting patterns to convert dates into readable strings for integrations, reports, or document generation. At first glance, the patterns YYYY and yyyy appear identical. However, they represent two different concepts of a year, and using the wrong one can produce unexpected results. This difference becomes especially noticeable around the start and end of a year, where a formatted date may unexpectedly display the wrong year value. Understanding this behavior can help developers avoid subtle bugs in Salesforce integrations, automation, and reporting processes. How Date Formatting Works in Apex In Salesforce Apex, Date and Datetime values can be formatted using the format() method. The formatting patterns follow the same conventions as Java’s SimpleDateFormat . Example Datetime dt = Datetime.newInstance(2024, 12, 31, 0, 0, 0); String formatted = dt.format(‘yyyy-MM-dd’); System.