-2

How can i add the hours, minutes, and seconds that exceeds in 24 hours given a string format time in php? ex.

$time1 = '10:50:00';
$time1 = '24:00:15';

where the result would be: '34:00:15'

iehrlich
  • 3,572
  • 4
  • 34
  • 43

1 Answers1

0

You won't be able to use typical date classes (like DateTime) or functions (like date()) to output hours beyond 24. So you'll have to do this manually.

First you will need to get the times into seconds, so that you can easily add them together. You can use the explode function to get the hours, minutes, and seconds, and multiply those values by the number of seconds required. (60 seconds is 1 minute. 60*60 seconds is 1 hour).

Then you'll need to output the total number of hours, minutes, and seconds. This can be achieved fairly easily through division (again 1 hour is 60*60 seconds, so divide the number of seconds by 60*60 to get the hours), and the modulus operator (%) to get the "remainder" of minutes and seconds.

<?php
// Starting values
$time1 = "10:50:00";
$time2 = "24:00:15";

// First, get the times into seconds
$time1 = explode(":", $time1);
$time1 = $time1[0] * (60*60)    // Hours to seconds
            + $time1[1] * (60)  // Minutes to seconds
            + $time1[2];        // Seconds

$time2 = explode(":", $time2);
$time2 = $time2[0] * (60*60)    // Hours to seconds
            + $time2[1] * (60)  // Minutes to seconds
            + $time2[2];        // Seconds

// Add the seconds together to get the total number of seconds
$total_time = $time1 + $time2;

// Now the "tricky" part: Output it in the hh:mm:ss format.
// Use modulo to determine the hours, minutes, and seconds.
// Don't forget to round when dividing.
print 
    //Hours
    floor($total_time / (60 * 60)) .
    // Minutes
    ":" . floor(($total_time % (60 * 60)) / 60) .
    // Seconds
    ":" . $total_time % 60;

    // The output is "34:50:15"
?>

Because you're new to PHP, I've done this using functions rather than DateTime, since OOP in PHP may make it harder for you to understand what is happening here. However, if you're learning OOP in PHP, it may be a fun exercise to rewrite my answer using DateTime.


Edit: I've realized that you can use date() to get the number of minutes and seconds, rather than a modulo. You can replace that last print statement with something like this, if you would like:

print 
    //Hours
    floor($total_time / (60 * 60)) .
    // Minutes
    ":" . date('i', $total_time) .
    // Seconds
    ":" . date('s', $total_time);
RToyo
  • 2,877
  • 1
  • 15
  • 22