Jump to content

[SOLVED] Get number of months between two dates


lindm

Recommended Posts

Trying to build a function that gets the number of months between two dates (format YYYY-MM-DD). Here is my script so far:

 

function months($date,$date2){
$date3=strtotime($date);
$date4=strtotime($date2);
$date5=$date4-$date3;
$date6=floor($date5/31536000*12);

print $date6+1;
}
months('2006-01-01','2006-02-14');

 

THis is not a consistent script...loose one month sometimes (for instance 2005-01-01 to 2005-12-31) which made me add (+1) month. This however affects for instance (2005-01-01 to 2005-01-02) which gives 1 month...HELP!

 

Got a better solution now..is this the best that goes?

function months($date,$date2){
$date3=strtotime($date);
$date4=strtotime($date2);
$date5=$date4-$date3;
$date6=round($date5/86400/30); //days and then months
print $date6;
}
months('2006-01-01','2007-04-30');

 

 

Dynamic Program

 

<?php

$date1 = "2006-01-15";

$date2 = "2007-02-02";


$date_1 = array();
$date_2 = array();

$date_1 = explode("-",$date1);
$date_2 = explode("-",$date2);

if($date_2[0] == $date_1[0]){
echo " Months ".($date_2[1]-$date_1[1]);
}elseif((strtotime($date2) - strtotime($date1))>0){
$cur_year = $date_2[0];
$months = 0;
do{
	if($cur_year == $date_2[0]){
		$months = $months + $date_2[1];
	}elseif($cur_year == $date_1[0]){
		$months = $months + (12 - $date_1[1]);
	}else{
		$months = $months + 12;
	}

	--$cur_year;

}while($cur_year >= $date_1[0]);
echo " Months ".$months;
}else{
echo "Date 2 should be greter than Date 1.";
}
?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.