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?
PHP date_diff() Function $date2=date_create("2013-12-12"); $diff=date_diff($date1,$date2);
You can convert them to timestamps and go from there: $hourdiff = round((strtotime($time1) - strtotime($time2))/3600, 1);
I'm not sure what format you're looking for in your difference but here's how to do it using DateTime
$datetime1 = new DateTime(); $datetime2 = new DateTime('2011-01-03 17:13:00'); $interval = $datetime1->diff($datetime2); $elapsed = $interval->format('%y years %m months %a days %h hours %i minutes %s seconds'); echo $elapsed;
You can simply use datetime diff and format for calculating difference.
<?php $datetime1 = new DateTime('2009-10-11 12:12:00'); $datetime2 = new DateTime('2009-10-13 10:12:00'); $interval = $datetime1->diff($datetime2); echo $interval->format('%Y-%m-%d %H:%i:%s'); ?>
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With