Search code examples
perldatetime

Why does DateTime's strftime give the wrong year when I subtract days from dates near the end of a year?


I have to open some logs that have a date in the filename. So I am trying to open all the files through a certain date.

I'm using DateTime. I do:

do 
{
    $datechoice = $today->strftime('%G%m%d'); #YearMonthDay
    $date_for_graph = $today->strftime('%d/%m/%G');
    # unshift @Log_Period_Time, "$date_for_graph";
    print $datechoice." - ".$date_for_graph."<br>";
    $today->subtract(days => 1);
} while($datechoice > 20141107);

But the output shows the wrong year for dates near the end of a year:

20160109 - 09/01/2016
20160108 - 08/01/2016
20160107 - 07/01/2016
20160106 - 06/01/2016
20160105 - 05/01/2016
20160104 - 04/01/2016
20150103 - 03/01/2015  <-- Should be 2016
20150102 - 02/01/2015
20150101 - 01/01/2015
20151231 - 31/12/2015
20151230 - 30/12/2015
20151229 - 29/12/2015
...
20150103 - 03/01/2015
20150102 - 02/01/2015
20150101 - 01/01/2015
20151231 - 31/12/2015
20151230 - 30/12/2015
20151229 - 29/12/2015
20141228 - 28/12/2014  <-- Should be 2015
20141227 - 27/12/2014
20141226 - 26/12/2014

Why is this happening?


Solution

  • Use %Y, not %G, unless you specifically mean to display the date according to the ISO 8601 week number calendar.

    (In the ISO calendar, every year is a whole number of weeks running Monday-Sunday. So whenever January 1st isn't a Monday there will be up to three days on one side of it that fall in the "wrong" year by ISO reckoning. For instance, ISO year 2021 started on Monday, January 4th; January 1st through 3rd fell in the last week of 2020. Going the other way, ISO year 2026 will start on Monday, December 29th, 2025, so the last 3 days of that December are already the first week of the next ISO year.)