Comparing dates giving incorrect outputs

后端 未结 2 1217
暖寄归人
暖寄归人 2021-01-27 13:14

I\'m creating a function to check which date, in a database table full of date\'s, is smaller then then current date. As in the past.

I\'ve got 3 date\'s to test the fun

相关标签:
2条回答
  • 2021-01-27 13:54

    You cant compare date string like that. Convert it to timestamp first. Use strtotime.

    $dateNow = date('d-m-Y H:i:s'); //Current
    $deadlineDate = "28-04-2015 16:33:18";
    
    if(strtotime($deadlineDate) < strtotime($dateNow)){ //If date from last month is smaller then the current date
        echo '<tr class="overdue">'; //Overdue class gives that tr an red background color to mark it
        echo '<td>'.$deadlineDate.' is smaller then '.$dateNow.'</td>';
    }else{
        echo '<tr>';
        echo '<td>'.$deadlineDate.' is bigger dan '.$dateNow.'</td>';
    }
    
    0 讨论(0)
  • 2021-01-27 14:12

    Your "dates" are really strings. And when comparing them it is alphabetical. You need to convert those dates to real dates for this to work:

    $dateNow = new DateTime();
    $deadlineDate = DateTime::createFromFormat("d-m-Y H:i:s", "28-04-2015 16:33:18");
    if($deadlineDate < $dateNow){ //If date from last month is smaller then the current date
        echo '<tr class="overdue">'; //Overdue class gives that tr an red background color to mark it
        echo '<td>'.$deadlineDate.' is smaller then '.$dateNow.'</td>';
    }else{
        echo '<tr>';
        echo '<td>'.$deadlineDate.' is bigger dan '.$dateNow.'</td>';
    }
    

    Converting them into YYYY-MM-DD format will also work.

    0 讨论(0)
提交回复
热议问题