Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Minus two dates in php [duplicate]

Tags:

php

datetime

i want to minus two dates in php

for example:

$date1 = 08/16/2013;
$date2 = 08/23/2013;
$answer = date2 - date1;

the $answer should be 7, How will i do that? thank you so much

like image 720
Albert Avatar asked Aug 23 '13 06:08

Albert


2 Answers

Start using DateTime class for date/time manipulation :

$date1 = new DateTime('08/16/2013');
$date2 = new DateTime('08/23/2013');
$diff = $date1->diff($date2);
print_r($diff); // or $diff->days

Output :

DateInterval Object
(
    [y] => 0
    [m] => 0
    [d] => 7
    [h] => 0
    [i] => 0
    [s] => 0
    [invert] => 0
    [days] => 7
)

Read more for DateTime:diff().


Please note that various strtotime() examples are not correct in date/time difference calculation. The simplest example is difference between 2013-03-31 21:00 and 2013-03-30 21:00. Which for naked eye is exact 1 day difference, but if you do subtract this 2 dates, you will get 82800 seconds which is 0.95833333333333 days. This is because of the time change from winter to summer time. DateTime handles leap years and time-zones properly.

like image 105
Glavić Avatar answered Oct 12 '22 01:10

Glavić


Try this -

<?php
$date1 = strtotime('08/16/2013');
$date2 = strtotime('08/23/2013');

echo $hourDiff=round(abs($date2 - $date1) / (60*60*24),0);
?>
like image 37
Chinmay235 Avatar answered Oct 12 '22 01:10

Chinmay235