Comparing two dates

2019-01-01 00:52发布

How can I compare two dates in PHP?

In the database, the date looks like 2011-10-2.

If I wanted to compare today's date against the date in the database to see which one is greater, how would I do it?

I tried this,

$today = date("Y-m-d");
$expire = $row->expireDate //from db

if($today < $expireDate) { //do something; }

but it doesn't really work that way. What's another way of doing it?

Update: I know this post is kinda old but i just wanted to mention carbon, which is a class thats used with laravel but can be used with classic php and it does wonders with dates. check it out: Carbon

标签: php date compare
13条回答
心情的温度
2楼-- · 2019-01-01 01:18

If all your dates are posterior to the 1st of January of 1970, you could use something like:

$today = date("Y-m-d");
$expire = $row->expireDate; //from database

$today_time = strtotime($today);
$expire_time = strtotime($expire);

if ($expire_time < $today_time) { /* do Something */ }

If you are using PHP 5 >= 5.2.0, you could use the DateTime class:

$today_dt = new DateTime($today);
$expire_dt = new DateTime($expire);

if ($expire_dt < $today_dt) { /* Do something */ }

Or something along these lines.

查看更多
余生无你
3楼-- · 2019-01-01 01:19

Just to compliment the already given answers, see the following example:

$today = new DateTime('');
$expireDate = new DateTime($row->expireDate); //from database



 if($today->format("Y-m-d") < $expireDate->format("Y-m-d")) { 
       //do something; 
    }

Update: Or simple use old-school date() function:

if(date('Y-m-d') < date('Y-m-d', strtotime($expire_date))){
  //echo not yet expired! 
}   
查看更多
还给你的自由
4楼-- · 2019-01-01 01:20
$today_date=date("Y-m-d");
$entered_date=$_POST['date'];
$dateTimestamp1 = strtotime($today_date);
$dateTimestamp2 = strtotime($entered_date);
$diff= $dateTimestamp1-$dateTimestamp2;
//echo $diff;
if ($diff<=0)
   {
     echo "Enter a valid date";
   }
查看更多
何处买醉
5楼-- · 2019-01-01 01:22
    while ($row=mysql_fetch_array($result))
    {


        $orderdate=explode('-',$row['alertdate']);
        $date=$orderdate[0];
        $month=$orderdate[1];
        $year=$orderdate[2];

        if((date(Y)>=$year) and (date(m)>=$month) and (date(d)>=$date))
        {
          //write your true code  

        }
        else
        {
          //write your false code 
        }
查看更多
人间绝色
6楼-- · 2019-01-01 01:24

Found the answer on VipDomaine blog and it's as simple as:

strtotime(date("Y"."-01-01")) -strtotime($newdate))/86400

And you'll get the days between the 2 dates.

查看更多
大哥的爱人
7楼-- · 2019-01-01 01:34

in the database the date looks like this 2011-10-2

Store it in YYYY-MM-DD and then string comparison will work because '1' > '0', etc.

查看更多
登录 后发表回答