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

Simply you can check..

if ($startdate < $date) {// do something} 
if ($startdate > $date) {// do something}

but both dates must be in same formatlike

Y-m-d or d-m-Y

etc.

查看更多
梦寄多情
3楼-- · 2019-01-01 01:35

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
查看更多
低头抚发
4楼-- · 2019-01-01 01:37

You can use simple PHP to compare dates:

$date = new simpleDate();
echo $date->now()->compare($expire_date)->isBeforeOrEqual();

This will give you true or false.

You can check the tutorials for more examples. Please click here.

查看更多
闭嘴吧你
5楼-- · 2019-01-01 01:41
$today = date('Y-m-d');//Y-m-d H:i:s
$expireDate = new DateTime($row->expireDate);// From db 
$date1=date_create($today);
$date2=date_create($expireDate->format('Y-m-d'));
$diff=date_diff($date1,$date2);
$timeDiff = $diff->format("%R%a days");

echo $timeDiff;
if($timeDiff < 0){
    echo "Expired.";
}else{
    echo "Not expired.";
}
查看更多
余生请多指教
6楼-- · 2019-01-01 01:42

first of all, try to give the format you want to the current date time of your server:

  1. Obtain current date time

    $current_date = getdate();

  2. Separate date and time to manage them as you wish:

$current_date_only = $current_date[year].'-'.$current_date[mon].'-'.$current_date[mday]; $current_time_only = $current_date['hours'].':'.$current_date['minutes'].':'.$current_date['seconds'];

  1. Compare it depending if you are using donly date or datetime in your DB:

    $today = $current_date_only.' '.$current_time_only;

    or

    $today = $current_date_only;

    if($today < $expireDate)

hope it helps

查看更多
骚的不知所云
7楼-- · 2019-01-01 01:44

I had that problem too and I solve it by:

$today = date("Ymd");
$expire = str_replace('-', '', $row->expireDate); //from db

if(($today - $expire) > $NUMBER_OF_DAYS) 
{ 
    //do something; 
}
查看更多
登录 后发表回答