PHPIntermediate

Calculating Hours Difference in PHP

PB Pb28 Master Team July 11th, 2022 Intermediate

📦 Get the complete source code for this tutorial

In PHP, there are many ways to calculate the difference between two dates. In this tutorial, we are using PHP date time functions to calculate the hour 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 the start and end date from the user.

php-hours-difference

php-template
<form id="frmDate" action="" method="post">

	<div>

	<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">

	</div>

	

	<div>

	<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">

	</div>

	

	<div>

	<input type="submit" name="submit" value="Find Difference" class="btnAction">

	</div>

</form>

PHP Function to Calculate Hours Difference

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

php
<?php

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 Demo

📦 Download the full project files and try it locally