How can I compare two dates in PHP? How can I compare two dates in PHP? php php

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.


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.


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

$today = new DateTime('');$expireDate = new DateTime($row->expireDate); //from databaseif($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! }