Find Time Between Two Dates in PHP

April 30th, 2012 by laeeq | No comments

As a PHP developer We often need a function to find time between two dates in PHP. So Here I have write a very simple PHP function that allows you to find the time between two dates. The dates must be in seconds from Unix timestamp.

if(!function_exists(timeBetweenTwoDates))
{
function timeBetweenTwoDates($start_date,$end_date)
{
$diff = $end_date-$start_date;
$seconds = 0;
$hours = 0;
$minutes = 0;if($diff % 86400 <= 0){$days = $diff / 86400;} // 86,400 this is seconds in a day if($diff % 86400 > 0)
{
$rest = ($diff % 86400);
$days = ($diff – $rest) / 86400;
if($rest % 3600 > 0)
{
$rest1 = ($rest % 3600);
$hours = ($rest – $rest1) / 3600;
if($rest1 % 60 > 0)
{
$rest2 = ($rest1 % 60);
$minutes = ($rest1 – $rest2) / 60;
$seconds = $rest2;
}
else{$minutes = $rest1 / 60;}
}
else{$hours = $rest / 3600;}
} 

if($days > 0){$days = $days.’ days, ‘;}
else{$days = false;}
if($hours > 0){$hours = $hours.’ hours, ‘;}
else{$hours = false;}
if($minutes > 0){$minutes = $minutes.’ minutes, ‘;}
else{$minutes = false;}
$seconds = $seconds.’ seconds’; // least one second

return $days.”.$hours.”.$minutes.”.$seconds;

}
}

Example:

$first_date = date(“U”);
$second_date = date(“U”, mktime(0,0,0,10,5,2011));
echo timeBetweenTwoDates($first_date, $second_date)”;

Hope it will work for you!

You can subscribe to PHPZAG.COM posts by Email

 

Related Topics:

  • Wrapping Text using PHP
  • PHP 5.5 beta 4 is now available
  • Swapping Array Keys and Values
  • PHP Security
  • Working with Image Metadata in PHP
  • Converting Between Relative and Absolute File Path
  • Parsing File Paths with PHP
  • How to remove HTML Comments with PHP?
  • How to access .htaccess values?
  • Dealing With Common PHP Errors
  • Interview Questions and Answers for Freshers
  • Display numbers with ordinal suffix using PHP
  • Function to set COLLATION on database fields of Mysql
  • Read and write to remote files using PHP
  • Sharing PHP SESSION Variables between Multiple Subdomains
  • PHP 5.5.0 Alpha4 Development Preview Released
  • Check a string starts with http using PHP
  • Cross-Site Scripting Attacks (XSS)
  • PHP 5.4.11 and PHP 5.3.21 released!
  • PHP Memory Leak Issue
  •  

     

    1. No comments yet.
    1. No trackbacks yet.