difference between two times in php – How to calculate the difference between two dates in PHP?

difference between two times in php – Calculate difference (in hours) between two times in PHP using strtotime and DateTime.

<?php
$time1 = strtotime('08:00:00');
$time2 = strtotime('09:30:00');
$difference = round(abs($time2 - $time1) / 3600,2);
echo $difference;

difference between two times in php

use strtotime() for time calculation

$joindt = strtotime('09:00:59');
echo 'Check Time : '.date('H:i:s', $joindt);
echo '<hr>';

$signinactivity = strtotime('09:01:00');
$diff = $joindt - $signinactivity;
echo 'Login Time : '.date('H:i:s', $signinactivity).'<br>';
echo ($diff < 0)? 'Late!' : 'Right time!'; echo '<br>';
echo 'Time diff in sec: '.abs($diff);

echo '<hr>';

$signinactivity = strtotime('09:00:59');
$diff = $joindt - $signinactivity;
echo 'Login Time : '.date('H:i:s', $signinactivity).'<br>';
echo ($diff < 0)? 'Late!' : 'Right time!';

echo '<hr>';

$signinactivity = strtotime('09:00:00');
$diff = $joindt - $signinactivity;
echo 'Login Time : '.date('H:i:s', $signinactivity).'<br>';
echo ($diff < 0)? 'Late!' : 'Right time!';

Get time difference between two times in PHP using DateTime class

Example

$time1 = new DateTime('2022-01-23 18:16:25');
$time2 = new DateTime('2020-01-23 11:36:28');
$checknow = $time1->diff($time2);
echo $checknow->format('%y year %m month %d days %h hour %i minute %s second')."<br/>";

Examples

echo $checknow->s."<br/>";
echo $checknow->i."<br/>";
echo $checknow->h."<br/>";
echo $checknow->d."<br/>";
echo $checknow->m."<br/>";
echo $checknow->y."<br/>";

PHP calculate time difference between two dates in hours and minutes

I hope you get an idea about difference between two times in php.
I would like to have feedback on my infinityknow.com blog.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.