Home > Software engineering >  Weird result in comparing dates in PHP
Weird result in comparing dates in PHP

Time:10-06

I have a simple function that counts number of weeks since a given date. The "active" week contains dates within a range. Each week start from a saturday and end on the next saturday. This was working fine untill today: 01/10/2021, instead of returning a positive number, the function now returns -1.

Here's the code:

public function getActiveWeek(){
    //1. Get the current date
    $current_date = date('d-m-Y H:i:s'); //now GTM 1

    //2.Define starting and ending week range
    $start_week = "18-09-2021 00:00:00";
    //Now, to get $end_week, we add 7 days 00h 00m 00s to $start_week
    $end_week = date('d-m-Y H:i:s', strtotime($start_week)   604800);
    //3. Check if the current date is between the starting and ending week range
    $current_week = 0;
    if ($current_date >= $start_week && $current_date <= $end_week) {
        echo "Current date is between the starting and ending week range";
        $current_week = $current_week;
    } else if ($current_date > $end_week) {
        echo "Current date is after the ending week range";
        //We count the weeks since $start_week
        $weeks_count = $this->getWeeksBetweenDates($start_week, $current_date);
        $current_week = $weeks_count; //was previously : $current_week   1;
    } else if ($current_date < $start_week) {
        echo "Current date is before the starting week range"; 
        echo $current_date . " < " . $start_week;
        $current_week = $current_week - 1;
    } else {
        throw new Exception("Some errors in getActiveWeek() function.");
    }

    return $current_week;
}

Now the problem is condition $current_date > $end_week is evaluated to false which leads to the next condition be evaluated to true ($current_date < $start_week). Changing $current_date to, say, "26-09-2021 00:00:00" works perfectly and the function returns 1.

What am I doing wrong? Thanks for your help.

CodePudding user response:

The solution was easy. I had to convert $start_week to date object and importantly the format was the issue as well. The below works solved my problem:

$start_week = date('Y/m/d H:i:s', strtotime($starting_date));
  • Related