Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP find difference between two datetimes

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?

like image 367
Staleyr Avatar asked Mar 28 '13 17:03

Staleyr


People also ask

How can I get the difference between two dates in PHP?

PHP date_diff() Function $date2=date_create("2013-12-12"); $diff=date_diff($date1,$date2);

How can I calculate hours between two dates in PHP?

You can convert them to timestamps and go from there: $hourdiff = round((strtotime($time1) - strtotime($time2))/3600, 1);


2 Answers

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; 
like image 107
John Conde Avatar answered Sep 22 '22 17:09

John Conde


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

like image 23
Nishu Tayal Avatar answered Sep 19 '22 17:09

Nishu Tayal