lindm Posted September 15, 2007 Share Posted September 15, 2007 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! Link to comment https://forums.phpfreaks.com/topic/69445-solved-get-number-of-months-between-two-dates/ Share on other sites More sharing options...
lindm Posted September 15, 2007 Author Share Posted September 15, 2007 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'); Link to comment https://forums.phpfreaks.com/topic/69445-solved-get-number-of-months-between-two-dates/#findComment-348944 Share on other sites More sharing options...
jitesh Posted September 15, 2007 Share Posted September 15, 2007 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."; } ?> Link to comment https://forums.phpfreaks.com/topic/69445-solved-get-number-of-months-between-two-dates/#findComment-348945 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.