开发者

Why doesn't PHP recognise when the date given is after today's date?

开发者 https://www.devze.com 2023-04-10 11:43 出处:网络
I want to compare two dates in PHP. One date is the date due, which is provided by the user, stored in a database and retrieved with PHP.

I want to compare two dates in PHP. One date is the date due, which is provided by the user, stored in a database and retrieved with PHP. The second is today's date.

    $unixdue = strtotime($query['date_due']); //Converts the database integer to Unix date
    $duestamp = date("dmY", $unixdue); //Converts the Unix date to dd-mm-yyyy


//If the due date is larger than toda开发者_StackOverflow中文版y (i.e., after today), it's early.
        if ($query['complete'] == 0 AND date("dmY") < $duestamp) {echo "Early";}
//If the due date is smaller than today (i.e., before today), it's late.
        elseif ($query['complete'] == 0 AND date("dmY") > $duestamp) {echo "Late";}
//If the due date IS today, it's today.
        elseif ($query['complete'] == 0 AND date("dmY") == $duestamp) {echo "Today";}

It works with dates that are today, but all the others return "Early" even if they are not early. Due to this I can't even tell if the rest is working at all.

I have tried comparing two Unix dates, but they include the time as well, when really I only want the date. If I compare two unix dates, I can't say if something is "Today".


You can't compare whether two strings are less than or greater than each other. Or you can, but in this case you shouldn't because the results are not what you want ("03092011" < "29082011" for example).

You can first compare if the dates are equal as you have done; if they are not, you can compare the timestamps. Even though you use only dates it doesn't matter because the timestamp of an earlier date is always smaller than the timestamp of a later date, regardless of the time part.

if( $query['complete'] == 0 ) {
    if( date("dmY") == $duestamp ) { echo "Today"; }
    elseif( time() < $unixdue ) { echo "Early"; }
    elseif( time() > $unixdue ) { echo "Late"; }
}


You are comparing in a wrong way.

A possible solution would be using date('Ymd') but even better is using timestamps as time() and the $unixdue


Use the time function:

$msg = "Late";

if( $unixdue > time() ){
$msg = "Early";
}

if(date("dmY") === $duestamp){
$msg = "Today";
}

Here is where it is documented.


you have overcomplicated your code by introducing unix timestamp, absolutely unnecessarily
and and it seems you have to move completeness check into SQL query. So

if     ($query['date_due'] > date("Y-m-d")) echo "Early";
elseif ($query['date_due'] < date("Y-m-d")) echo "Late";
else echo "Today";

and I believe you can move this condition into query too

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号