简体   繁体   中英

How to check if a date has passed

I am trying to check if a date has passed or if it is the future. If the end_date has passed then I do not want it to display. end_date is a MySQL timestamp. Right now all news articles are displaying even if their end_date has passed. Here is the code I am using to check if the date has passed:

function dateExp( $timestamp ){

   $exp = intval($timestamp);
   $today = intval( time() );


   if( $exp > today ) return true;
   else return false;

}

Here is the code that gets the articles and displays them:

$qry = "select *    
         from   news
         where  display='Y'
         order by priority, date_added, title";

$news = _execQry($qry);


foreach( $news as $n )
{
   if( dateExp($n['end_date']) ){
      echo '<h3>'. $n['title'] .'</h3>';
      echo '<p>'. $n['story'] ;
      echo '<br />Added on '. dateFormat($n['date_added']) .'</p><br />';
   }

}

I suggest that you trim the records inside the query that way you program has less data to process.

$qry = "select *
from news
where display='Y' and end_date >= CurDate()
order by priority, date_added, title";

The problem is with the dateExp function. You're missing a $ sign. Because of that PHP interprets today as a constant instead of $today which is the variable you're using to hold the current timestamp..

It should be like this:

function dateExp( $timestamp )
{

$exp = intval($timestamp);
$today = intval( time() );


if( $exp > $today ) return true;
else return false;

}

As a matter of fact you can streamline the function a little bit more:

function dateExp($timestamp)
{
   $timestamp = intval($timestamp);  // make sure we're dealing wit 'numbers'
   return ($timestamp > time());     // return TRUE if $timestamp is in the future
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM