-2

I want to get the Time in and Time out then get the rendered hours, minutes and seconds but im having a problem on subtracting time here is a sample result

Time in: 10:00:33 Time out: 10:01:30

Total Hours rendered: 0 Total Minutes rendered: 1 Total Seconds rendered: -3

in the sample above it returns 1 minute already even though its not 1 minute yet and in the seconds it returns a negative value

here is my code

$time_out = date("H:i:s");
$nerd->time_out = $time_out;
$time_o = explode(":", $time_out);
$time = explode(":", $nerd->time_in);
$hours = $time_o[0] - $time[0];
$minutes = $time_o[1] - $time[1];
$seconds = $time_o[2] - $time[2];   

if($minutes < 2){
   $minutes_r = 0;
}else if($minutes <= 15){
   $minutes_r = 15;
}else if($minutes <= 30){
   $minutes_r = 30;
}else if($minutes <= 45){
   $minutes_r = 45;
}else{
   $minutes_r = 0;
}

in my code I explode the time to get values in hours, minutes and seconds.

Can anyone suggest a better way of doing this so there will be no negative results?

Ace
  • 83
  • 2
  • 10
  • 1
    Use unix time. There is no way to go wrong with that. Then do all operations on numbers of seconds, instead of dividing them into hours/minutes. – Dimi Mar 24 '17 at 02:40
  • see this http://stackoverflow.com/questions/365191/how-to-get-time-difference-in-minutes-in-php – bato3 Mar 24 '17 at 03:02
  • Why am having negative votes? – Ace Mar 24 '17 at 03:24
  • Possible duplicate of [How to get time difference in minutes in PHP](http://stackoverflow.com/questions/365191/how-to-get-time-difference-in-minutes-in-php) – Rocketq Mar 24 '17 at 07:04
  • @Ace: because you work on parts. When `2.3 - 1.4` = `2 - 1 + 0.3 - 0.4` = `1 + (-0.1)` you stop on this.. BTW: use timestamp: `$minutes = (strtotime('2000-01-01 '.$time_out) - strtotime('2000-01-01 '.$time_in) )/60;` – bato3 Mar 24 '17 at 13:32

1 Answers1

1

add this in middle:

  if($seconds < 0) {
        $seconds += 60; 
        $minutes--;
  }
  if($minutes < 0) {
        $minutes += 60; 
        $hours--;
  }
bato3
  • 2,695
  • 1
  • 18
  • 26