I needed to display a list of dates by collating dates that are next to each other into “date ranges”.

If the dates are siblings (next to each other, like today, yesterday and the day before yesterday), put the startdate-enddate and then put following dates, if they stand alone, separated with commas, or as other date ranges.

So for example:
The dates are ‘1973-10-16’, ‘1973-10-17’, ‘1973-10-18’, ‘1973-10-19’, ‘1973-10-22’

And it should be shown as

“1973-10-16 to 1973-10-19, 1973-10-22″

This is how i did it. If you can optimize it, i’m all ears !! Also, i can’t seem to make it work with a UK date format… yet.
[PHP]

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 ‘

';
print_r($dates);

$dateRanges = detectDateRanges($dates);

print_r($dateRanges);

[/PHP]