0

Possible Duplicate:
How to find number of days between two dates using php

If I have two dates - how do I find the real difference in days between two dates? You must take things like leap years and the number of days in each month into account.

How many days are between something like 2010-03-29 and 2009-07-16?

Community
  • 1
  • 1
Xeoncross
  • 55,620
  • 80
  • 262
  • 364

3 Answers3

11

strtotime and simple math:

   $daylen = 60*60*24;

   $date1 = '2010-03-29';
   $date2 = '2009-07-16';

   echo (strtotime($date1)-strtotime($date2))/$daylen;
netcoder
  • 66,435
  • 19
  • 125
  • 142
  • 2
    `echo abs(floor((strtotime("2010-03-29")-strtotime("2009-07-16"))/(60*60*24)));` – Xeoncross Dec 21 '10 at 18:58
  • 1
    I agree with `abs`, but not `floor`. Those are days being compared to days, `floor` or not, same result. Besides, the number of days between X and Y might be 232.67 and it's still valid (unless OP specifically asked for it to be rounded). – netcoder Dec 21 '10 at 19:07
  • Above solution gives exactly, result is in + or - days. – bharatesh Feb 19 '14 at 10:29
  • in regions with daylight savings time, some days have 23/25 hours. You will run into trouble then. Use DateTime. – i4h Feb 15 '15 at 02:05
4

check out PHP DateTime class. It deals with all the gory details so you can just do regular subtraction.

$d1=date_create('1999-10-23');
$d2=date_create('2004-04-17');

$i=date_diff($d2,$d1);
echo $i->format('%a');
dnagirl
  • 20,196
  • 13
  • 80
  • 123
  • 1
    1. This should be $i->format('%d') (forgot the %) 2. For the total number of days use '%a' 3. There is a bug in the Windows version that will always return 6015 when using this function (see https://bugs.php.net/bug.php?id=51184) – Hirnhamster Nov 19 '13 at 14:34
  • it doesn't work properly, i get sometimes 0 when i try to play with months value – ImadT Dec 03 '13 at 04:09
3

Here you go:

<?php
$date1 = strtotime("2010-03-29");
$date2 = strtotime("2009-07-16");
$dateDiff = $date1 - $date2;
$fullDays = floor($dateDiff/(60*60*24));
echo "Differernce is $fullDays days";
?>
THE DOCTOR
  • 4,399
  • 10
  • 43
  • 64