Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding two time values in php

Tags:

php

    $test=strtotime("06:30:00")+strtotime("03:00:00");

    echo gmdate("H:i:s", $test);

This gives the wrong answer ( 23:01:44 ).

    $test=strtotime("06:30:00")-strtotime("03:00:00");

    echo gmdate("H:i:s", $test);

while subtracting same code gives me the right answer( 03:30:00 ).

like image 400
Snooze Avatar asked May 12 '26 02:05

Snooze


2 Answers

You should do this:

<?
echo date("H:i:s", strtotime("06:30:00 + 3 hour"));
echo date("H:i:s", strtotime("06:30:00 - 3 hour"));
?>
like image 64
Adam Avatar answered May 13 '26 17:05

Adam


Your logic is wrong. If you'll act like in 1-st sample, you'll sum two timestamps as they are (i.e. starting from 0) - so you'll count previous time twice. If you are subtracting them, however, you're getting 'expected' result because each operand's previous period eliminates another.

But that's not how it's supposed to work. You should use DateTime API to work with dates and periods in PHP.

like image 35
Alma Do Avatar answered May 13 '26 17:05

Alma Do



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!