DateTime.format() unexpected behavior

Hi I am executing following code snippet and after 26/12/2015, date shifted to one year ahead of expected.

Date startDate = Date.parse('12/24/2015');
Date endDate = Date.parse('12/30/2015');

while(startDate <= endDate){
    Datetime localDateTime = startDate;
    startDate = startDate.addDays(1);
    System.debug('~~~~~localDateTime'+localDateTime);
    System.debug('~~~~~localDateTime'+localDateTime.format('MM/dd/YYYY'));
}

And following is the debug

19:14:17.040 (40027257)|EXECUTION_STARTED
19:14:17.040 (40036021)|CODE_UNIT_STARTED|[EXTERNAL]|execute_anonymous_apex
19:14:17.040 (40989828)|USER_DEBUG|[7]|DEBUG|~~~~~localDateTime2015-12-24 00:00:00
19:14:17.041 (41059958)|USER_DEBUG|[8]|DEBUG|~~~~~localDateTime12/24/2015
19:14:17.041 (41128835)|USER_DEBUG|[7]|DEBUG|~~~~~localDateTime2015-12-25 00:00:00
19:14:17.041 (41163269)|USER_DEBUG|[8]|DEBUG|~~~~~localDateTime12/25/2015
19:14:17.041 (41222037)|USER_DEBUG|[7]|DEBUG|~~~~~localDateTime2015-12-26 00:00:00
19:14:17.041 (41254864)|USER_DEBUG|[8]|DEBUG|~~~~~localDateTime12/26/2015
19:14:17.041 (41312303)|USER_DEBUG|[7]|DEBUG|~~~~~localDateTime2015-12-27 00:00:00
19:14:17.041 (41345356)|USER_DEBUG|[8]|DEBUG|~~~~~localDateTime12/27/2016
19:14:17.041 (41402820)|USER_DEBUG|[7]|DEBUG|~~~~~localDateTime2015-12-28 00:00:00
19:14:17.041 (41434519)|USER_DEBUG|[8]|DEBUG|~~~~~localDateTime12/28/2016
19:14:17.041 (41493306)|USER_DEBUG|[7]|DEBUG|~~~~~localDateTime2015-12-29 00:00:00
19:14:17.041 (41525359)|USER_DEBUG|[8]|DEBUG|~~~~~localDateTime12/29/2016
19:14:17.041 (41582636)|USER_DEBUG|[7]|DEBUG|~~~~~localDateTime2015-12-30 00:00:00
19:14:17.041 (41613956)|USER_DEBUG|[8]|DEBUG|~~~~~localDateTime12/30/2016

Any Idea why it is happening ?

Thanks

Answer

Actually… the datetime format is right.

The capital Y merge field is the WEEK YEAR – which from the 27th December 2015 is IN 2016!

The lower case y merge field is the CALENDAR YEAR – which will be 2015 as expected.

Change your line to

System.debug('~~~~~localDateTime'+localDateTime.format('MM/dd/yyyy'));

and you will see your logs play properly.

Notes: The Datetime.Format uses the Java SimpleDateFormat library/technology, documentation for which you can find here.

Attribution
Source : Link , Question Author : ashishcloud , Answer Author : Simon Lawrence

Leave a Comment