PHP compare two dates

2019-08-03 22:20发布

I have two dates in the format YYYY-MM-DD and I want to compare them do do some task.

I tried this piece of code:

         $temp_date = strtotime($cu['date']);
         $temp_upto = strtotime($upto_date);

         if($temp_date <= $temp_upto){
            echo "<tr id='highlight'>"; 
        }else{
            echo "<tr>";
            }

$cu is an array and contains date in the same format. Is this the correct way to compare dates in php? The output which I get is quite weird! I haven't posted the full code because its too long and irrelevant for this question. Thanks!.

UPDATE: So this is what I am trying to do. I have many normal dates and I have a upto date if the normal dates are less than or equal to upto date then I want the id="highlight" added to . THe whole thing is inside a loop for some other purpose of my code.

I echoed the dates like this:

 echo "DATE: " . $temp_date + " UPTO: " . $upto_date;

and the output was something like

DATE: 1349042400 UPTO: 00-00-0000
DATE: 1349388000 UPTO: 00-00-0000
DATE: 1352588400 UPTO: 00-00-0000
DATE: 1352761200 UPTO: 00-00-0000
DATE: 1353193200 UPTO: 00-00-0000
DATE: 1353366000 UPTO: 1353193200
DATE: 1354143600 UPTO: 1353193200
DATE: 1354662000 UPTO: 1353193200

still the comparison doesn't happen. and I dont see any change!

People who are suggestion already answered questions, I have already read and implemented most of them without any success.

UPDATE 2: While I am still trying to figure out my issue. I want to share the expanded code snippet here http://pastebin.com/nsVGV9dg

2条回答
兄弟一词,经得起流年.
2楼-- · 2019-08-03 22:27

I'm not directly answering your question but I thinks it's better to user php DateTime object.

$datetime1 = new DateTime('2009-10-11');
$datetime2 = new DateTime('2009-10-13');
$interval = $datetime1->diff($datetime2);
查看更多
放我归山
3楼-- · 2019-08-03 22:34

Nope, this isn't right. You're comparing two date strings. You want to compare the timestamps instead:

$temp_dateTS = strtotime($cu['date']);
$temp_uptoTS = strtotime($upto_date);

if ($temp_dateTS <= $temp_uptoTS) {
    # code...
}

This is also possible (and better) if you use DateTime class:

$temp_date = new DateTime($cu['date']);
$temp_upto = new DateTime($upto_date);

if ($temp_date <= $temp_upto) {
    # code...
}
查看更多
登录 后发表回答