December 29, 2020

DateTime.valueOf() returning next year date for December month dates

In valueOf(), the specified string should use the standard date format “yyyy-MM-dd HH:mm:ss”.

Formatting using YYYY(Uppercase) is NOT the same as yyyy(Lowercase). So, change YYYY(Uppercase) to yyyy(Lowercase) to fix this issue.

Reference Link - https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_methods_system_datetime.htm
 
Sample Code:
String customDateFieldValue = '2020-03-12 20:03:20';
System.debug( DateTime.valueOf( customDateFieldValue ).format( 'yyyy-MM-dd' ) );
customDateFieldValue = '2020-12-29 20:03:20';
System.debug( DateTime.valueOf( customDateFieldValue ).format( 'YYYY-MM-dd' ) );


Output:

 

No comments:

Post a Comment