calculate days difference b/w 2 dates

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
yaron
Forum Contributor
Posts: 157
Joined: Fri Aug 22, 2003 8:40 am

calculate days difference b/w 2 dates

Post by yaron »

Hello all,

I have 2 dates in yyyy-mm-dd format.
I need to calculate the difference (in number of days ) between those 2 dates.
I had some ideas but none of them came through...
any thought on how to crack this one up?

Thank u all
qads
DevNet Resident
Posts: 1199
Joined: Tue Apr 23, 2002 10:02 am
Location: Brisbane

Post by qads »

php.net.....the manual :lol:

Code: Select all

<?php
/*T.E.
07-Jan-2004 04:15 
Most functions calculating the difference in days between two days take some assumptions. They often ignore leap-years or decide to set a month to 30 days. This one here should work better and more precise.
I left one thing to fix: I supposed a leap in every four years. This assumption is wrong when passing a xx00-border, if xx00 mod 400 != 0. However, PHPs date-function won't work with 1900 or less and 2100 or more. So for the next few years within the given boarders of PHP, this one should work.*/
function date_diff($dat1,$dat2)
/* Dat1 and Dat2 passed as "YYYY-MM-DD" */
{
  $tmp_dat1 = mktime(0,0,0,
     substr($dat1,5,2),substr($dat1,8,2),substr($dat1,0,4));
  $tmp_dat2 = mktime(0,0,0,
     substr($dat2,5,2),substr($dat2,8,2),substr($dat2,0,4));

  $yeardiff = date('Y',$tmp_dat1)-date('Y',$tmp_dat2);
  /* a leap year in every 4 years and the days-difference */
  $diff = date('z',$tmp_dat1)-date('z',$tmp_dat2) + 
           floor($yeardiff /4)*1461;

  /* remainder */
  for ($yeardiff = $yeardiff % 4; $yeardiff>0; $yeardiff--)
   {
     $diff += 365 + date('L',
         mktime(0,0,0,1,1,
           intval(
             substr(
               (($tmp_dat1>$tmp_dat2) ? $dat1 : $dat2),0,4))
           -$yeardiff+1));
   }

  return $diff;
} 
?>
User avatar
markl999
DevNet Resident
Posts: 1972
Joined: Thu Oct 16, 2003 5:49 pm
Location: Manchester (UK)

Post by markl999 »

Another example that makes some assumptions ;)

Code: Select all

<?php
$date1 = '2004-01-28';
$date2 = '2004-01-12';
echo (strtotime($date1) - strtotime($date2)) / (60*60*24).' days difference';
?>
yaron
Forum Contributor
Posts: 157
Joined: Fri Aug 22, 2003 8:40 am

Post by yaron »

Thx very much...
seems to work fine !!
Post Reply