Loading

Apex Datetime Class Sometimes Returns Incorrect Year

게시 일자: Oct 13, 2022
상세 설명
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.
솔루션
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 기사 번호

000380991

 
로드 중
Salesforce Help | Article