Comparing dates giving incorrect outputs

北慕城南 提交于 2019-12-02 22:49:46

问题


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 function with, and the outputs behind them:

Date from last month: 28-04-2015 16:32:00
Date yet to come: 11-06-2015 13:12:00
Date from last week: 04-05-2015 09:45:00

$dateNow = date('d-m-Y H:i:s'); //Current
$deadlineDate = "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>';
}

</tr>

Outputs:

28-04-2015 16:32:00 Returns bigger
11-06-2015 13:12:00 Returns smaller
04-05-2015 09:45:00 Returns smaller

Can anybody tell me what is going wrong?


回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/30190082/comparing-dates-giving-incorrect-outputs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!