Home » Blogging

PHP: Format and show an expiration date

A useful routine to calculate and show an expiration date based on a given number of hours

// Hours to expiration
$iHrs = 72;
// Date from database
$dbDate = '2008-04-08 16:53:19';
// obtain current date and time
$iTimeNow = date("U");
// calculate expiry time
$iExpiryTime = ($iHrs * 3600) + strtotime("$dbDate") ;
// set the message to display
$strMessage = "";
// compare times
if ($iTimeNow < $iExpiryTime)
{
  $strMessage = "Expiry time has been reached!';
}
else
{
  // compute the difference in times
  $iTimeLeft = $iExpiryTime - $iTimeNow;
  // breakdown the results
  $days = floor($iTimeLeft / 86400);
  $hours = floor(($iTimeLeft - $days * 86400) / 3600);
  $mins = floor(($iTimeLeft - $days * 86400 - $hours * 3600) / 60);
  $secs = floor($iTimeLeft - $days * 86400 - $hours * 3600 - $mins * 60);
  // show the results
  $strMessage = 'Time to expiry: ' . $days . ' days ' . $hours . ' hours ' . $mins . ' min and ' . $secs . ' seconds';
}
echo $strMessage;
?>

Related Posts with Thumbnails

Leave a comment!

Add your comment below, or trackback from your own site. You can also subscribe to these comments via RSS.

Be nice. Keep it clean. Stay on topic. No spam.

You can use these tags:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

This is a Gravatar-enabled weblog. To get your own globally-recognized-avatar, please register at Gravatar.