0

I want to calculate difference of two time in php (just time without Date). both time are in format AM/PM 12Hours like "6:35 PM" and "7:30 AM". how can i calculate difference and show result in minute. some codes in php like this

$time1 =' 6:30 AM';
$time2 = '7:45 AM';
$result = $time1 - $time2;
echo $result->format('%hh %im'); ///////////// show 1h 15m
if ($result(h) <1)  ///////////////////////// if hours less than 1 hours
  echo "do some things";
if ($result(h) >1)  ////////////////////////if hours more than 1 hours
  echo "do some things";

thank you very much

  • 1
    You could combine [this information](https://stackoverflow.com/questions/365191/how-to-get-time-difference-in-minutes-in-php) with `DateTime`'s [`createFromFormat`](https://www.php.net/manual/en/datetimeimmutable.createfromformat.php). – El_Vanja Dec 20 '20 at 15:24

1 Answers1

0
$time1 = '6:30 AM';
$time2 = '7:45 AM';

// Convert to unix timestamp, relative to now
$time1 = strtotime($time1);
$time2 = strtotime($time2);

// Difference in seconds
$result = abs($time1 - $time2);

$hours = floor($result / 3600);  // 1 (hr)
$hour_minutes = floor(($result % 3600) / 60);  // 15 (min)
$minutes = floor($result / 60);  // 75 (min)
loydg
  • 229
  • 2
  • 3