2

I need to show the difference between two times in PHP I use strtotime() function to convert my times to integer but my problem is the result not matched what I expected

<?php
$hour1 = '12:00:00';
$hour2 = '9:00:00';
$avg = strtotime($hour1) - strtotime($hour2);
$result = date('h:i:s', $avg); // result = 06:30:00 what I expected is 3:00:00

But the difference is 3:00:00 how to calculate this?

Amir Hossein
  • 916
  • 2
  • 13
  • 38

2 Answers2

3

You can create DateTime instances and use diff function to get the difference between 2 times. You can then format them in hours,minutes and seconds.

<?php

$hour1 = '12:00:00';
$hour2 = '09:00:00';

$o1 = new DateTime($hour1);
$o2 = new DateTime($hour2);

$diff = $o1->diff($o2,true); // to make the difference to be always positive.

echo $diff->format('%H:%I:%S');

Demo: https://3v4l.org/X41pv

nice_dev
  • 17,053
  • 2
  • 21
  • 35
0

You can do that:

$hour1 = '12:00:00';
$hour2 =  date('h', strtotime('9:00:00')); 
$avg= date('h:i:s', strtotime($hour1. ' - '.$hour2.' hours') );
echo $avg; //3:00:00
Simone Rossaini
  • 8,115
  • 1
  • 13
  • 34