How can I compare two dates?

04/11/2020 00:30:01

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

Verified Answer (75 Votes)

10/03/2010 03:31:12

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.

75

Answer #2 (218 Votes)

10/03/2010 03:25:06

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.

218

Answer #3 (22 Votes)

10/01/2013 17:27:27

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! 
}   
22
3
Hack Hex uses Stack Exchance API by the Stack Exchange Inc. to scrape questions/answers under Creative Commons license.