datetime - PHP: Wrong Time Calculation
235
I am working on a project and writing a function to add two different times. The times are stored in database as a string.
I'm:
- Pulling value from db
- converting it into time using
strtotime
- adding times using
date
function
Here is my code:
$time_1 = '1:00';
$time_2 = '0:05';
//should be 1:05, whereas it prints 04:05
echo date("H:i", strtotime($time_1) + strtotime($time_2));
Please tell me, what is wrong with above code and how it can be fixed?
Thanks
Answer
Solution:
Your problem is because
returns the number of seconds since the Unix Epoch (Jan 1 1970). So what you are getting is not values of
60
and5
, but something more like1537570800
and1537567500
. When you add those two values together, you end up with a date far in the future, with what looks effectively like a random time. To compensate for this, you need to subtract the value ofstrtotime
at the start of the day to make the second time a relative time e.g.:Output:
Update
Since it turns out that the sum of the two times can exceed 24 hours, the above code will not work (the maximum time it will display is
23:59
before rolling over to00:00
. So it is necessary to convert both times to a relative number of minutes to the start of the day, add them and then display as hours and minutes:Output:
Answer
Solution:
Use DateTime::createFromFormat function, and taking ideas from Adding two DateTime objects in php
Additional Details: