linein designs

04 Apr, 2008

Find Time Between Two Dates in PHP

Posted by: john In: php| programing

Below is a quick PHP function that allows you to find the time between two dates. The dates must be in seconds from Unix Epoch.

if(!function_exists(timeBetween))
{
	function timeBetween($start_date,$end_date)
	{
		$diff = $end_date-$start_date;
 		$seconds = 0;
 		$hours   = 0;
 		$minutes = 0;

		if($diff % 86400 <= 0){$days = $diff / 86400;}  // 86,400 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'; // always be at least one second

		return $days.''.$hours.''.$minutes.''.$seconds;
	}
}

Usage Example:

$one_date = date("U");
$two_date = date("U", mktime(0,0,0,4,1,2008));
echo timeBetween($one_date, $two_date).'';
// displays "x days, x hours, x minutes, x seconds"

Similar Posts:

No related posts.

Tags:

2 Comments »

Comment by laptop satış

php is easy programmer language . . .

forewer asp.net . . .

 
Name (required)
E-mail (required - never shown publicly)
URI
Your Comment (smaller size | larger size)
You may use <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> in your comment.

Trackback responses to this post



Please Support Our Sponsors

A Payday advance can be a great way to get back on track.

Banner

About

My name is John Veldboom and have been in design and web programing for just over 8 years now. Started off as a hobby in high school but it has developed into a full time job now. I always tell people that if I wasn't doing this at work each day, I would be at home doing it for free. I love it!

Please visit the contact page to drop me a message.