Forum Moderators: coopster
find a simple way for PHP to work out the days for each month when the reservation crosses one or more month ends.
<?php
function monthDaysBetween($dateA, $dateB) {
$ts1 = strtotime($dateA);
$ts2 = strtotime($dateB);
$a = array();
$month = date('F', $ts1); //string name of month, such as "July"
$year = date('Y', $ts1); //four digit year
$prop = $month.' '.$year;
$a[$prop] = 0;
while ($ts1 < $ts2) {
$a[$prop]++;
$ts1 += 86400; //86400 seconds in a day
$tmpMonth = date('F', $ts1); //string name of month, such as "July"
if ($tmpMonth !== $month) { //we are in to the next month
$month = $tmpMonth;
$year = date('Y', $ts1); //four digit year
$prop = $month.' '.$year;
$a[$prop] = 0;
}
}
return $a; //array of numbers of nights stayed in particular months betweent the two dates
}
//a number of arrays of arrival and departure dates for testing:
$tests = array(
array('arrival' => '2011-03-25', 'departure' => '2011-05-03'),
array('arrival' => '2011/7/24', 'departure' => '2011/7/29'),
array('arrival' => '2011-8-27', 'departure' => '2011-9-3'),
array('arrival' => '2011-03-25', 'departure' => '2012-05-03')
);
foreach ($tests as $arr) {
$arrival = $arr['arrival'];
$departure = $arr['departure'];
$nightsStayed = monthDaysBetween($arrival, $departure);
$totalNights = array_sum($nightsStayed);
echo "<p>Arrive: $arrival, Depart: $departure<br>Total Nights: $totalNights</p>";
echo '<pre>';
print_r($nightsStayed);
echo '</pre><hr>';
}
?>
return $a;
if ($a[$prop] === 0) {
unset($a[$prop]);
}
return $a;
print_r($nightsStayed);
foreach ($nightsStayed as $monthYear => $nights) {
echo $monthYear.' : '.$nights.' nights stayed<br>';
}