PHP: date comparison

Discussion in 'Web Design and Development' started by Antowns, Sep 18, 2009.

  1. Antowns macrumors member

    Joined:
    Jul 24, 2009
    #1
    Hi guys,

    I've tried and can't figure this out. I would like to make an expiration script. For example, if todays date was stored in the database as the 'expiry' date it would of obviously been reached so the executed code would return that it had expired. Any help would be nice ;)
     
  2. Cerebrus' Maw macrumors 6502

    Joined:
    Mar 9, 2008
    Location:
    Brisbane, Australia
    #2
    Using the strtotime php function, you can get the date from the database and if its an ISO standard date format, use strtotime to get the number of seconds since the Epoch, and then compare it to the current number of seconds NOW since the Epoch. If the date has a larger number of seconds, it is in the future. if it is less, it is in the past.

    I'm going to assume that we have pulled the date from our databse, and placed in a $row variable, with a named field of expiry_date. The date is in the yyyy-mm-dd format. (strtotime is pretty robust, so other European Formats like dd-mm-yyyy, dd--mm-yy, d-m-yy, should also work)

    Code:
     <?php
         $date_seconds = strtotime ($row[expiry_date]); #Seconds for the expiry date
         $now_seconds = time(); #Seconds for NOW
         if ($date_seconds<=$now_seconds)
        {
            /**Date is in the past or is today, expiry date reached **/
        }
        else
        {
            /**Date is in the future, do something **/
        }
    ?>
    
    Watch the <= operator. Setting it as <= will mean that the expiry_date IS the limit. If you set it to <, will mean that the expiry date will execute the code if that date is now.
     
  3. Tom Sawyer macrumors 6502a

    Tom Sawyer

    Joined:
    Aug 29, 2007
    #3
    For what it's worth, I chose to go this route as I needed the actual # of days difference, worked out well for leaving the dates in SQL friendly format as well....

    function daysDifference($endDate, $beginDate)
    {
    //explode the date by "-" and storing to array
    $date_parts1=explode("-", $beginDate);
    $date_parts2=explode("-", $endDate);
    //gregoriantojd() Gregorian to Julian date format
    $start_date=gregoriantojd($date_parts1[1], $date_parts1[2], $date_parts1[0]);
    $end_date=gregoriantojd($date_parts2[1], $date_parts2[2], $date_parts2[0]);
    return $end_date - $start_date;​
    }
     
  4. NoNameBrand macrumors 6502

    Joined:
    Nov 17, 2005
    Location:
    Halifax, Canada
    #4
    If the date is stored in the ISO format (YYYY-MM-DD - it should be), then simple alphanumeric comparisons will work properly.

    PHP:
    if ($expiryDate <= date('Y-m-d')) {
          
    //expired
    }
     
  5. Antowns thread starter macrumors member

    Joined:
    Jul 24, 2009

Share This Page