In my PHP application I want to calculate the sum of two time variables. I am looking for something like this example.
$time1 = 15:20:00;
$time2 = 00:30:00;
$time = $time1+$time2;
In my PHP application I want to calculate the sum of two time variables. I am looking for something like this example.
$time1 = 15:20:00;
$time2 = 00:30:00;
$time = $time1+$time2;
If the answer you expect is 15:50:00
and you want to use strtotime
and date
functions, you need to subtract the seconds $time1
and $time2
share when you transform them to unix timestamps:
$time1 = '15:20:00';
$time2 = '00:30:00';
$time = strtotime($time1) + strtotime($time2) - strtotime('00:00:00');
$time = date('H:i:s', $time);
The best way to do this is most likely to use strtotime to convert them to timestamps and then do the adding together:
$o = strtotime($time1)+strtotime($time2);
If I remember right strtotime
does support this format.
Otherwise you will need to filter it out yourself.
Following answer does not return correct value. It is summing integers but not returned correct time.
$o = strtotime($time1)+strtotime($time2);
I created a function to get calculated time as follows.
public function addTwoTimes($time1 = "00:00:00", $time2 = "00:00:00"){
$time2_arr = [];
$time1 = $time1;
$time2_arr = explode(":", $time2);
//Hour
if(isset($time2_arr[0]) && $time2_arr[0] != ""){
$time1 = $time1." +".$time2_arr[0]." hours";
$time1 = date("H:i:s", strtotime($time1));
}
//Minutes
if(isset($time2_arr[1]) && $time2_arr[1] != ""){
$time1 = $time1." +".$time2_arr[1]." minutes";
$time1 = date("H:i:s", strtotime($time1));
}
//Seconds
if(isset($time2_arr[2]) && $time2_arr[2] != ""){
$time1 = $time1." +".$time2_arr[2]." seconds";
$time1 = date("H:i:s", strtotime($time1));
}
return date("H:i:s", strtotime($time1));
}
You could use the PHP 5.3 DateInterval
:
$timeInterval = DateInterval::createFromDateString( '15 hours + 20 minutes' );
$timeInterval2 = DateInterval::createFromDateString( '30 minutes' );
foreach( str_split( 'ymdhis' ) as $prop )
{
$timeInterval->$prop += $timeInterval2->$prop;
}
var_dump( $timeInterval->format( '%H:%i:%s' ) );
(How to add to DateInterval objects was explained here: How we can add two date intervals in PHP)
As far as I can tell, Sammaye's answer did't work out for me.
I needed to start the time I wanted to add with the start of the UNIX timestamp. This way, strtotime
returns the seconds that need to be added to the first time.
$time1 = "15:20:00";
$time2 = "1970-01-01 00:30:00";
$time = strtotime($time1) + (strtotime($time2) + 3600);
echo $time . "<br />";
echo date("H:i:s", $time);
Be sure to consult the mystic docs http://us1.php.net/strtotime for additional things you can input into your functions :)
$today = time();
$tommorrow = strtotime("+1 days", $today);
$day_after_tomorrow = strtotime("+1 days", $tomorrow);
Code:
$time1 = '15:20:00';
$time2 = '00:30:00';
$time = strtotime($time1)+strtotime($time2);
$sumtime = date("H:i:s",$time);