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:45

Here's a way on how to get the difference between two dates in minutes.

// set dates
$date_compare1= date("d-m-Y h:i:s a", strtotime($date1));
// date now
$date_compare2= date("d-m-Y h:i:s a", strtotime($date2));

// calculate the difference
$difference = strtotime($date_compare1) - strtotime($date_compare2);
$difference_in_minutes = $difference / 60;

echo $difference_in_minutes;
查看更多
登录 后发表回答