11

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

Albert
  • 327
  • 1
  • 3
  • 16
  • `$datetime1 = new DateTime($date1); $datetime2 = new DateTime($date2); $days = round(($datetime1->format("U") - $datetime2->format("U")) / 86400);` It will return number integer of days. – Dũng IT Nov 07 '16 at 04:41

4 Answers4

24

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.

Glavić
  • 42,781
  • 13
  • 77
  • 107
3

Try this -

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

echo $hourDiff=round(abs($date2 - $date1) / (60*60*24),0);
?>
Chinmay235
  • 3,236
  • 8
  • 62
  • 93
0

You can get with strtotime and minus dates

$diff = abs(strtotime('08/16/2013') - strtotime('08/23/2013'));

echo $min = floor($diff / (60*60*24)); // 7
Bora
  • 10,529
  • 5
  • 43
  • 73
  • why you divide the diff to (60*60*24)? and where do you get that? – Albert Aug 23 '13 at 06:43
  • `60*60*24` is second of days. `diff` result is `604800` about betweeen two date seconds. You have to divide to day. First `60` is min, second `60` hour and last `24` is for the day. So `60*60*24 = 86400` is mean one(1) date. – Bora Aug 23 '13 at 06:47
  • How many days difference is from `2013-03-31 21:00` to `2013-03-30 21:00` with this example? – Glavić Aug 23 '13 at 06:51
  • This is not same format with question. As question format, this is totaly right. No need to force @Glavić – Bora Aug 23 '13 at 06:55
  • The problem is, that strtotime() is not ok method for date/time calculation. And the answer should also support time in my humble opinion. – Glavić Aug 23 '13 at 06:58
-1
$date1 = '08/16/2013';
$date2 = '08/23/2013';
$days = (strtotime($date2) - strtotime($date1)) / (60 * 60 * 24);
print $days; 
Yasitha
  • 2,233
  • 4
  • 24
  • 36