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

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:

Help Article for reference – https://help.salesforce.com/articleView?id=000332268&type=1&mode=1

Leave a Reply