...

View Full Version : Displaying a date range from an array of dates



flamy
12-10-2008, 12:05 PM
I have an array of dates:

15-12-2008,16-12-2008,17-12-2008,18-12-2008,19-12-2008,22-12-2008,23-12-2008,24-12-2008,25-12-2008,26-12-2008,

I'd like to display them like:

15-12-2008 to 19-12-2008
22-12-2008 to 26-12-2008

Surely somebody has already written a function to do this?

I presume I'd need to put all 2008 dates into a separate array, then the months, then do something like loop through the days and if the next array item is the value +1 then loop until it is not +1 to give me the range. But then, what if the range goes between months e.g. 27-02-2008 to 13-03-2008.

Any help or an already written function to do this would be gratefully appreciated. :)

flamy
12-10-2008, 12:17 PM
5 minutes after posting this I found this:


function detectDateRanges($dates)
{
// $dates is an array
$result = array();
$tempDateRange = '' ;
foreach($dates as $index => $date) {
/*
Example: $dates=array('1973-10-16','1973-10-17','1973-10-18','1973-10-19','1973-10-22');
*/
if ($index != 0) {
$dayBeforeDate = strtotime('-1 day', strtotime($date));
$previousDateInArray = strtotime($dates[$index-1]);
/*
if previously stored date is NOT just before current date, separate them in returned array
*/
if ($previousDateInArray != $dayBeforeDate) {
if ($tempDateRange !== $dates[$index-1]) {
$tempDateRange .= ' to ' . $dates[$index-1];
}
/*
Store the previous tempValue and start a new temptative dateRange
*/
$result[] = $tempDateRange;
$tempDateRange = $date ;
}
} else {
$tempDateRange = $date ;
}
} // end foreach
/*
Finish processing the last date
*/
if ($tempDateRange !== $date) {
$tempDateRange .= ' to ' . $dates[$index];
} else {
$tempDateRange = $date ;
}
$result[] = $tempDateRange;
return $result;
}
$dates=array('1973-10-16','1973-10-17','1973-10-18','1973-10-19','1973-10-22');
echo '
<pre>';
print_r($dates);
$dateRanges = detectDateRanges($dates);
print_r($dateRanges);

Courtesy of: http://www.pixeline.be/blog/2006/php-detect-date-ranges-in-a-series-of-dates/

Problem solved :)



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum