I'm trying to get the difference between two datetimes and return it as a datetime. I've found examples using diff but i can't seem to get it right.
$timein = date("Y-m-d H:i:s");
$timeout = date("Y-m-d 20:00:00");
$totaltime = $timein->diff($timeout);
However $totaltime logs "0000-00-00 00:00:00" to my DB. Is this because i'm not formatting my totaltime variable?
John Conde does all the right procedures in his method but doesn't satisfy the final step in your question which is to format the result to your specifications.
This code (Demo) will display the raw difference, expose the trouble with trying to immediately format the raw difference, display my preparation steps, and finally present the correctly formatted result:
Output:
Now to explain my datetime value preparation:
$details
takes the diff object and casts it as an array. array_flip(['y','m','d','h','i','s']) creates an array of keys which will be used to remove all irrelevant keys from(array)$diff
using array_intersect_key().Then using array_map() my method iterates each value and key in
$details
, pads its left side to the appropriate length with0
's, and concatenates the$r
(result) string with the necessary separators to conform with requested datetime format.You can simply use datetime diff and format for calculating difference.
For more information OF DATETIME format, refer: here
You can change the interval format in the way,you want.
Here is the working example
P.S. These features( diff() and format()) work with >=PHP 5.3.0 only
I'm not sure what format you're looking for in your difference but here's how to do it using DateTime