0
votes

I have durations in %RH:i:s format (like +00:00:00 or -00:00:00) and I want to add or subtract them (with the negative) and not in 24 hours

Ex :

1/ (09:30:15+(-10:00:00)) = -01:30:15.

2/ 22:00:00 + 03:00:00 = 25:00:00 (not 01:00:00 +1day)

Any idea ? Thanks in advance !

EDIT:

Finally did it. Don't know if it's the real right way to do it but it works pretty well. Found it by the help of another function found on a forum.

function calc_hours($hour1,$hour2){
    
    $si1 = $hour1[0]; $si2 = $hour2[0]; 
    
    $hour1 = substr($hour1,1,8);
    $hour2 = substr($hour2,1,8);        
    
    $secondes1=intval($si1.heure_to_secondes($hour1));
    $secondes2=intval($si2.heure_to_secondes($hour2));
    
    $somme=intval($secondes1+$secondes2);
    
    //transfo en h:i:s
    $s= ($somme % 60); 
    $m1=   (($somme-$s) / 60);
    $m= ($m1 % 60);
    $h= (($m1-$m) / 60); 
    
    if($somme > 0) { $sif = '+'; }
    $resultat=sprintf("%02d", $h).":".sprintf("%02d", abs($m)).":".sprintf("%02d", abs($s))."";
    return  $sif.$resultat;
}

function heure_to_secondes($heure){
    $array_heure=explode(":",$heure);
    $secondes=3600*$array_heure[0]+60*$array_heure[1]+$array_heure[2];
    return $secondes;
}

Call it like : calc_hours('+27:45:16','-02:35:12');

1
Yes, don't use date() or the datetime class. - Daan
Any more info ? What do I use if I can't use date() or datetime class ? - hellodracon
You have to create a formula yourself. A datetime always will calculate with 24 hours. - Daan
Thanks. But that's all the point of my question. I'm looking for help, to make this formula. - hellodracon

1 Answers

0
votes

Finally did it. Don't know if it's the real right way to do it but it works pretty well. Found it by the help of another function found on a forum.

function calc_hours($hour1,$hour2){

    $si1 = $hour1[0]; $si2 = $hour2[0]; 

    $hour1 = substr($hour1,1,8);
    $hour2 = substr($hour2,1,8);        

    $secondes1=intval($si1.heure_to_secondes($hour1));
    $secondes2=intval($si2.heure_to_secondes($hour2));

    $somme=intval($secondes1+$secondes2);

    //transfo en h:i:s
    $s= ($somme % 60); 
    $m1=   (($somme-$s) / 60);
    $m= ($m1 % 60);
    $h= (($m1-$m) / 60); 

    if($somme > 0) { $sif = '+'; }
    $resultat=sprintf("%02d", $h).":".sprintf("%02d", abs($m)).":".sprintf("%02d", abs($s))."";
    return  $sif.$resultat;
}

function heure_to_secondes($heure){
    $array_heure=explode(":",$heure);
    $secondes=3600*$array_heure[0]+60*$array_heure[1]+$array_heure[2];
    return $secondes;
}

Call it like : calc_hours('+27:45:16','-02:35:12');