Loading

Apex Datetime Class Sometimes Returns Incorrect Year

Publish Date: Oct 13, 2022
Description
The Apex Datetime Class is commonly used to format datetime values into local times. Depending on the date value, the formatted value could display the wrong calendar year.
Resolution
The sample code below has a date near the end of the calendar year and uses 'YYYY' for the year format so it would return the formatted year as 2020 rather than the expected value of 2019. The Apex Datetime class uses the Java SimpleDateFormat which utilizes the capital 'Y' to return the value for the calendar year of that week and the lowercase 'y' as the year for the day. In order to ensure your code returns the year for a particular day, use the lowercase 'y' format for the dateFormatString.
 
Datetime GMTDate = 
  Datetime.newInstanceGmt(2019, 12, 30, 6, 0, 0);
String strConvertedDate = 
  GMTDate.format('MM/dd/YYYY HH:mm:ss', 
                 'Asia/Dubai');
The sample code returns the following values when using the different year formats discussed above:

strConvertedDate = '12/30/2020 10:00:00' when 'YYYY' is used
strConvertedDate = '12/30/2019 10:00:00' when 'yyyy' is used

Java References:
SimpleDateFormat
GregorianCalendar 
Knowledge Article Number

000380991

 
Loading
Salesforce Help | Article