Calculating Hours Difference in PHP

In PHP, there are many ways to calculate the difference between two dates. In this tutorial, we are using PHP datetime functions to calculate the hours difference between two dates.

In this example we are start and end dates from the user. And then, we use strtotime() to convert the date string into timestamp to calculate the difference.

View Demo


HTML Datetime Input

This code shows the input field to get start and end dates from the user.

<form id="frmDate" action="" method="post">
	<label style="padding-top:20px;">Start Date</label><br/>
	<input type="text" name="startdate" value="<?php if(!empty($_POST["startdate"])) { echo $_POST["startdate"]; } ?>" class="demoInputBox">
	<label>End Date</label>
	<span id="userEmail-info" class="info"></span><br>
	<input type="text" name="enddate" value="<?php if(!empty($_POST["startdate"])) { echo $_POST["enddate"]; } ?>" class="demoInputBox">
	<input type="submit" name="submit" value="Find Difference" class="btnAction">

PHP Function to Calculate Hours Difference

We call this PHP function when the user submitting the date ranges to calculate the hours difference.

function differenceInHours($startdate,$enddate){
	$starttimestamp = strtotime($startdate);
	$endtimestamp = strtotime($enddate);
	$difference = abs($endtimestamp - $starttimestamp)/3600;
	return $difference;
if(!empty($_POST["submit"])) {
	$hours_difference = differenceInHours($_POST["startdate"],$_POST["enddate"]);	
	$message = "The Difference is " . $hours_difference . " hours";

View DemoDownload

This PHP code tutorial was published on April 15, 2015.

↑ Back to Top