How can I compare two dates in PHP?

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.


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! 
}   

I would'nt do this with PHP. A database should know, what day is today.( use MySQL->NOW() for example ), so it will be very easy to compare within the Query and return the result, without any problems depending on the used Date-Types

SELECT IF(expireDate < NOW(),TRUE,FALSE) as isExpired FROM tableName

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.

Tags:

Php

Date

Compare