Calculating Hours Difference in PHP

by Vincy. Last modified on July 11th, 2022.

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.


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

Written by Vincy, a web developer with 15+ years of experience and a Masters degree in Computer Science. She specializes in building modern, lightweight websites using PHP, JavaScript, React, and related technologies. Phppot helps you in mastering web development through over a decade of publishing quality tutorials.

Leave a Reply

Your email address will not be published. Required fields are marked *

↑ Back to Top

Share this page