I've popped this up as I needed to work out the number of dates in between two dates. Again something similar might be out there, but I thought it may be useful for any one out there that may need it.
Parameters
Required - date1 and date2: Dates in the following format yyyy-mm-dd
Optional - inclusive: If you set to true it includes the two provided dates in it's calculation
Optional - return format of the dates: Combination of PHP's date formatting options
Return Values
Returns an array of dates and the number of days
The Code
/**
* Get the difference between two dates...
* @param string $date1 yyyy-mm-dd
* @param string $date2 yyyy-mm-dd
* @param boolean $inclusive
* @param string $return format
*
* @return array of total number of days and the dates in the prescribed format
*/
function days_between($date1, $date2, $inclusive = true, $return_format = 'Y-m-d') {
$date_array = array();
$output_array = array();
$date1_ts = strtotime($date1);
$date2_ts = strtotime($date2);
$second_difference = $date2_ts-$date1_ts;
$num_days = floor($second_difference / 86400);
if (is_numeric($num_days) && $num_days > 0) {
for ($i = 0; $i <= $num_days; $i++) {
$new_day = $date1_ts + ($i*86400);
$date_array[] = date($return_format,$new_day);
}
if (!$inclusive) {
unset($date_array[0]);
array_pop($date_array);
}
$output_array['number_of_days'] = sizeof($date_array);
$output_array['dates_between'] = $date_array;
}
return ($output_array);
}
Usage
days_between('2011-12-31', '2012-01-05', 1,'d M Y');
Labels: PHP, PHP date