// $p_hour_data['p_hour']=02:00:00
// $data['dapr_p_hour']=01:00:00
// answer is=01:00:00
$total_hour=((strtotime($p_hour_data['p_hour']))-(strtotime($data['dapr_p_hour'])));
echo $total_hour=gmdate("H:i:s", $total_hour);
The given code is for subtracting the time the value of the $p_hour_data['p_hour']=02:00:00
and $data['dapr_p_hour']=01:00:00
.
It gives the result right 00:01:00
.
But when I change it to addition it gives wrong answer 09:31:44
.
Why it happen like that any solution for time addition operation?
The problem is that you don't specify the time zone: for instance (using php -a
interactive mode):
> echo gmdate("H:i:s",strtotime('01:00:00'));
00:00:00
If you however add "UTC"
to all time stamps, the correct result shows up.
The reason is that if you don't specify the time zone, PHP will look at the server settings and assume the time is expressed in the time zone specified by the server. This means that 02:00:00
is parsed in Belgium as 01:00:00 UTC
. For subtraction this is not a problem (unless day saving time plays a part as well). For addition however, one needs to have a convention when a day starts. By adding UTC
however, the time is less ambiguous.
Example (using php -a
):
$ php -a
php > echo gmdate("H:i:s
",strtotime('02:00:00 UTC')+strtotime('01:00:00 UTC'));
03:00:00
php > echo gmdate("H:i:s
",strtotime('02:00:00 UTC')-strtotime('01:00:00 UTC'));
01:00:00
php > echo gmdate("H:i:s
",strtotime('02:00:00')-strtotime('01:00:00'));
01:00:00
php > echo gmdate("H:i:s
",strtotime('02:00:00')+strtotime('01:00:00'));
01:00:00
Your problem is not a timezone issue as @CommuSoft
mentioned. It's an "integer" overflow value issue.
Taking in mind that strtotime returns a UNIX Timestamp value (a bit large value but still in integers values range for your system), but adding another timestamp value to it (another big value) results to a integer overflow which PHP handles by converting the result to float ; see here.
strtotime('02:00:00'); //int(1419213600)
strtotime('01:00:00'); //int(1419210000)
strtotime('02:00:00') + strtotime('01:00:00'); //float(2838423600)
(int) (strtotime('02:00:00') + strtotime('01:00:00')); //int(-1456543696)
//Values can vary due to different default time zone ;)
Once the result passed to date
function, it will be converted back to integer
=> -145..... (some negative value) and your timestamp is equivalent to 1923-11-05 21:31:44
.
Hope it helps you find out the problem.