Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

Antowns

macrumors member
Original poster
Jul 24, 2009
97
0
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 ;)
 
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.
 
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;​
}
 
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
}
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.