note 51713 deleted from function.strtotime by derick
| From: | derick@php.net | Date: | Sun, 15 Jul 2007 12:49:40 +0000 |
| Subject: | note 51713 deleted from function.strtotime by derick | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-128588@lists.php.net to get a copy of this message | ||
Note Submitter: Greg Robbins
----
This function will count fractional months between 2 dates, perhaps for billing purposes (like for
hosting, as was my case).
<?php
function count_months($start_date, $end_date)
{
//Initialize counters for days and months
$days = 0;
$months = 0;
//get current month (as of your start_date)
$curr_month = date("Y-m-01", $start_date);
//loop by days
while($start_date <= $end_date)
{
//If the current iteration has passed on to a new month
if($curr_month != date("Y-m-01", $start_date))
{
//divide the number of days counted by the number of days in the month
//to get a decimal representation of how many months should be counted.
//Increment the months count by this value
$months += $days / date("t", strtotime($curr_month));
//Uncomment the following line to see how it counts month by month
//echo "$days Days / " . date("t", strtotime($curr_month)) . " days in
month $curr_month<br>\n";
//Advance the current month
$curr_month = date("Y-m-01", strtotime($curr_month . " + 1 months"));
//Reset the days counter sibce we are now counting a new month
$days = 0;
}
//Advance tot he next day...
$start_date = strtotime(date("Y-m-d", $start_date) . " + 1 days");
//And increment the day counter
$days++;
}
//This is the same as above but applied to the last month
$months += $days / date("t", strtotime($curr_month));
//Uncomment the following line to see how it counts month by month
//echo "$days Days / " . date("t", strtotime($curr_month)) . " days in
month $curr_month<br>\n";
//This returns a decimal value to two decimals of accuracy
return sprintf("%01.2f", $months);
}
//Check it out:
$last_billed_date = "2004-12-31";
$bill_thru_this_date = "2005-04-15";
$unix_start_date = strtotime($last_billed_date . " +1 days");
$unix_end_date = strtotime($bill_thru_this_date);
echo "Last billed date: " . $last_billed_date . "<br>";
echo "Bill through date: " . $bill_thru_this_date . "<br>";
echo "Total months: " . count_months($unix_start_date, $unix_end_date);
?>