-2

I want to compare two times which is in 12hrs format, but before comparing I have converted into strtotime and passed converted values to function and comparing it but output return 0 even there is time difference of 60 minutes still getting 0 in output.

<?php 

function timediff($start, $end)
{
    if($end >= $start) {
        return (round(($end-$start)/3600, 0))." Hrs ".((($end-$start)%3600)/60)." Min"; // time should be in queue
    } else {
        return (round(($start-$end)/3600, 0))." Hrs ".((($start-$end)%3600)/60)." Min";
    }
}

echo timediff(strtotime('09: am'), strtotime('08: am'));
Ne Ma
  • 1,719
  • 13
  • 19
msp
  • 127
  • 1
  • 12
  • 2
    Stop messing around with strtotime and trying to do the math by yourself. Do it _properly_ - use `DateTime` objects, and their `diff` method. – 04FS Feb 05 '20 at 11:59
  • 1
    this already has an answer [how-to-get-time-difference-in-minutes-in-php](https://stackoverflow.com/a/12382882/8484512) – danish-khan-I Feb 05 '20 at 12:00
  • Good code indentation would help us read the code and more importantly it will help **you debug your code** [Take a quick look at a coding standard](http://www.php-fig.org/psr/psr-2/) for your own benefit. You may be asked to amend this code in a few weeks/months and you will thank me in the end. – RiggsFolly Feb 05 '20 at 12:00
  • Duplicate question https://stackoverflow.com/questions/13741507/calculating-the-time-differencein-hours-and-minutes-using-strtotime – Ronak Dhoot Feb 05 '20 at 12:05

1 Answers1

0

you should pass a valid time string, try it

function timediff($start, $end) {
    if ($end >= $start) {
        return (round(($end - $start) / 3600, 0)) . " Hrs " . ((($end - $start) % 3600) / 60) . " Min";
    } else {

        return "-" . (round(($start - $end) / 3600, 0)) . " Hrs " . ((($start - $end) % 3600) / 60) . " Min";
    }
}

echo timediff(strtotime('09:00 am'), strtotime('08:00 am'));
AZinkey
  • 5,209
  • 5
  • 28
  • 46