Re: Date Math

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



On Tue, Apr 20, 2010 at 03:32:58PM -0400, tedd wrote:

> At 11:40 AM -0400 4/20/10, Floyd Resler wrote:
>> I need to get the difference in months between two dates.  The dates
>> could be as much as 60 months apart.  Is there any easy way to do
>> this either through PHP or MySQL?  I know how I can do it through
>> code but thought there might be a simple one or two line option.
>>
>> Thanks!
>> Floyd
>>
>
>
> <?php
>
> $date1 = '2009-02-27';
> $date2 = '2004-12-03';
>
> $udate1 = strtotime($date1);
> $udate2 = strtotime($date2);

$from = getdate($udate1);
$from_year = $from['year'];
$from_month = $from['month'];

$to = getdate($udate2);
$to_year = $to['year'];
$to_month = $to['month'];

// Assumes $to_date is later than $from_date

if ($from_year == $to_year)
	$months = $to_month - $from_month;
elseif ($to_month >= $from_month) {
	$num_years = $to_year - $from_year;
	$add_months = $num_years * 12;
	$base_months = $to_month - $from_month;
	$months = $base_months + $add_months;
}
else { // $to_month < $from_month
	$num_years = $to_year - $from_year;
	$base_months = $num_years * 12;
	$sub_months = $from_month - $to_month;
	$months = $base_months - $sub_months;
}

This will give the months between two dates, ignoring the actual day of
the month for each date (may not be exactly what you want, and code is
untested).

>
> $difference = $udate1 - $udate2;
>
> $months_difference = floor($difference / 2678400);
>
> echo("The difference is $months_difference months");
>
> ?>
>
> I this will work, but the question of what constitutes a month might
> come into play.

My code above is submitted because I don't like doing calculations with
seconds. Tedd's right, the OP's questions can't be answered precisely
because months vary in number of days.

Paul

-- 
Paul M. Foster

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux