Nathaniel P writes: “We have long agreed never to ask ‘why’ for any code in this project. We can only speculate, and therein lies madness.”

There’s a lot to speculate about in this block. Like so much bad code, it touches upon that favorite source of bad code: date handling. And, at its core, this code is actually fine, but it still puzzles us:

$theFirst = date("Y-m", strtotime("-1 months"));
list($theFirstYear, $theFirstMonth) = explode('-', $theFirst);
$theSecond = date("Y-m", strtotime("-2 months"));
list($theSecondYear, $theSecondMonth) = explode('-', $theSecond);
$theThird = date("Y-m", strtotime("-3 months"));
list($theThirdYear, $theThirdMonth) = explode('-', $theThird);

//this is a fix for weird feb issue
$date = new DateTime();
$theFirstMonth = $date->format('m')-1;
if(strlen($theFirstMonth) < 2){
    $theFirstMonth = '0'.$theFirstMonth;
}
$theSecondMonth = $date->format('m')-2;
if(strlen($theSecondMonth) < 2){
    $theSecondMonth = '0'.$theSecondMonth;
}

$theThirdMonth = $date->format('m')-3;
if(strlen($theThirdMonth) < 2){
    $theThirdMonth = '0'.$theThirdMonth;
}

$dateArray =  array($theThirdYear.'-'.$theThirdMonth,$theSecondYear.'-'.$theSecondMonth,$theFirstYear.'-'.$theFirstMonth);

The goal of this code is to output “Y-m”- year and month- for the past three months. And the core approach- pull the date with a format string for strtotime with dates like -1 months does the job. And that could be all of the code, but there was a weird feb issue. No one knows what this weird issue was, or what the fix was trying to do to fix it. The “fix” is to prepend a “0” to the front of the dates, but the logic is a mystery. Just a few lines before, they showed they knew how to do date arithmetic, but now they get the month and simply subtract a number, meaning in January and February, they’ll prepend zeros to the wrong month.

Hey, I think I figured out what the “weird feb issue” was.

This code doesn’t fix the issue, and quite to the contrary, creates the bug. This bug doesn’t need to exist, either. If we check the docs on PHP’s date format strings, we see that the “m” is: “Numeric representation of a month, with leading zeros”.

Nathaniel didn’t ask “why”, and leaves that to us. He just fixed it.

[Advertisement] ProGet can centralize your organization's software applications and components to provide uniform access to developers and servers. Check it out!