How can I compare two dates in PHP?

前端 未结 13 2019
一整个雨季
一整个雨季 2020-11-22 06:02

How can I compare two dates in PHP?

The date is stored in the database in the following format

2011-10-2

If I wanted to

相关标签:
13条回答
  • 2020-11-22 06:46

    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; 
    }
    
    0 讨论(0)
  • 2020-11-22 06:51

    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
    
    0 讨论(0)
  • 2020-11-22 06:52

    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! 
    }   
    
    0 讨论(0)
  • 2020-11-22 06:54

    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;
    
    0 讨论(0)
  • 2020-11-22 06:54

    If you want a date ($date) to get expired in some interval for example a token expiration date when performing a password reset, here's how you can do:

    $date = $row->expireDate;
    
    $date->add(new DateInterval('PT24H')); // adds 24 hours
    
    $now = new \DateTime();
    
    if($now < $date) { /* expired after 24 hours */ }
    

    But in your case you could do the comparison just as the following:

    $today = new DateTime('Y-m-d');
    
    $date = $row->expireDate;
    
    if($today < $date) { /* do something */ }
    
    0 讨论(0)
  • 2020-11-22 06:56

    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.

    0 讨论(0)
提交回复
热议问题