0

I could not find a method to help me do the following. I am given the following two time values: PT1H30M and PT1H45M. My goal is to add the two time values together to get PT2H5M.

Are there any functions or a more efficient way to write this?

This is what I did for each of the arguments that was passed through:

  • Remove PT from the time value.
  • Extract ??H and ??M into separate variables.
  • Removed H and M from those variables and made sure the remaining values is of int type.
  • Added the two hour values together as well as the two minute values.
  • If the sum of minutes exceeded 59 it is broken down and added to the hours.
  • The results is returned as the sum of the two time values.

Here is my code sample:

//* _h is short for hours and _m is short for minutes
function iso8601TimeSum($t1 = '', $t2 = '') {
    if(!$t1 && !$t2)
        return '';

    //remove PT 
    $t1 = str_replace('PT', '', $t1);
    $t2 = str_replace('PT', '', $t2);

    //extract ??[H|h] and ??[M|m] 
    $t1h_found = preg_match('/[00-59][Hh]/i', $t1, $t1_h);
    $t1m_found = preg_match('/[00-59][Mm]/i', $t1, $t1_m);
    $t2h_found = preg_match('/[00-59][Hh]/i', $t2, $t2_h);
    $t2m_found = preg_match('/[00-59][Mm]/i', $t2, $t2_m);

    //remove H|h and M|m from extracted values
    if($t1h_found)
        $t1_h = intval(preg_replace('/[Hh]/i', '', $t1_h[0]));

    if($t1m_found)
        $t1_m = intval(preg_replace('/[Mm]/i', '', $t1_m[0]));

    if($t2h_found)
        $t2_h = intval(preg_replace('/[Hh]/i', '', $t2_h[0]));

    if($t2m_found)
        $t2_m = intval(preg_replace('/[Mm]/i', '', $t2_m[0]));

    //add it together
    $calc_t_h = (!empty($t1_h) ? $t1_h : 0) + (!empty($t2_h) ? $t2_h : 0);
    $calc_t_m = (!empty($t1_m) ? $t1_m : 0) + (!empty($t2_m) ? $t2_m : 0);

    //if minutes exceeds 59 break it down and add it to the hours.
    if($calc_t_m > 59) {
        $calc_t_h += round($calc_t_m / 60);
        $calc_t_m = $calc_t_m % 60;
    }

    return 'PT' . ($calc_t_h > 0 ? $calc_t_h . 'H' : '00H') . ($calc_t_m > 0 ? $calc_t_m . 'M' : '00M');
}

var_dump(iso8601TimeSum('PT1H30M', 'PT1H45M'));
//*/
  • Those are [`DateInterval`](http://php.net/manual/class.dateinterval.php) strings, not *"time values"* – Phil Apr 10 '15 at 06:36

1 Answers1

0

You should use DateTime objects, there are handy functions that parse dates based on format: check http://php.net/manual/en/datetime.createfromformat.php

DateTime objects can also be used with math operations. I personally use this wrapper: https://github.com/briannesbitt/Carbon

Implementing your logic will be significanlty easier then

darioguarascio
  • 1,077
  • 11
  • 15