views:

229

answers:

4

Is there anyway to find the month difference in php? I have the input of from date 2003-10-17 and todate 2004-03-24. I need the results how many month is there within these two days. Say if 6 months, i need the output in months only. Thanks for guide me for day difference.

I find the solution through mysql but i need in php. Anyone help me, Thanks in advance.

+4  A: 

Here's a quick one:

$date1 = mktime(0,0,0,10,0,2003); // m d y, use 0 for day
$date2 = mktime(0,0,0,3,0,2004); // m d y, use 0 for day

echo round(($date2-$date1) / 60 / 60 / 24 / 30);
Kai Sellgren
This will become more and more inaccurate the farther apart the two dates are and may eventually round the wrong way...
deceze
+3  A: 

http://www.php.net/manual/en/datetime.diff.php

This returns a DateInterval object which has a format method.

Jeba Singh Emmanuel
+1  A: 
<?php
  # end date is 2008 Oct. 11 00:00:00
  $_endDate = mktime(0,0,0,11,10,2008);
  # begin date is 2007 May 31 13:26:26
  $_beginDate = mktime(13,26,26,05,31,2007);

  $timestamp_diff= $_endDate-$_beginDate +1 ;
  # how many days between those two date
  $days_diff = $timestamp_diff/2635200;

?>

Reference: http://au.php.net/manual/en/function.mktime.php#86916

Russell Dias
Same problem as @Kai's solution, very optimistic assumption that a month has 30 days...
deceze
+1  A: 

The easiest way without reinventing the wheel. This'll give you the full months difference. I.e. the below two dates are almost 76 months apart, but the result is 75 months.

date_default_timezone_set('Asia/Tokyo');  // you are required to set a timezone

$date1 = new DateTime('2009-08-12');
$date2 = new DateTime('2003-04-14');

$diff = $date1->diff($date2);

echo (($diff->format('%y') * 12) + $diff->format('%m')) . " full months difference";
deceze