Select Page

There are a number of ways to find the difference between two time stamps in PHP.  I needed to find the number of hours for a project with a time clock.  Here is an example you can test using the DateTime class.

		$date1 = new DateTime('2004-03-01T01:30:00');
		$date2 = new DateTime('2004-03-02T02:30:00');
		$diff = $date2->diff($date1);
		$hours = $diff->h;
		$hours = $hours + ($diff->format('%d')*24);
		$hours = $hours + ($diff->format('%i')/60); 
                // output our result with 2 decimal places
		printf('Hours: %s',number_format($hours,2));

You can edit the date values to test the result.  It will also take into account leap years if you want to be assured of the results.