比较 PHP 中日期的奇怪结果

Weird result in comparing dates in PHP

我有一个简单的函数,可以计算自给定日期以来的周数。 “活动”周包含一个范围内的日期。每周从一个星期六开始,到下一个星期六结束。直到今天,它一直运行良好:2021 年 1 月 10 日,函数现在没有返回正数,而是 returns -1.

代码如下:

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;
}

现在的问题是条件 $current_date > $end_week 被评估为 false,这导致下一个条件被评估为 true ($current_date < $start_week)。将 $current_date 更改为“26-09-2021 00:00:00”可以完美运行,函数 returns 1.

我做错了什么?感谢您的帮助。

解决方法很简单。我必须将 $start_week 转换为日期对象,重要的是格式也是问题所在。以下作品解决了我的问题:

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