PHP detect date ranges in a series of dates

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:
  1. function detectDateRanges($dates)
  2. {
  3. // $dates is an array
  4. $result = array();
  5. $tempDateRange = '' ;
  6. foreach($dates as $index => $date) {
  7. /*
  8. Example:  $dates=array('1973-10-16','1973-10-17','1973-10-18','1973-10-19','1973-10-22');
  9. */
  10. if ($index != 0) {
  11. $dayBeforeDate = strtotime('-1 day', strtotime($date));
  12. $previousDateInArray = strtotime($dates[$index-1]);
  13. /*
  14. if previously stored date is NOT just before current date, separate them in returned array
  15. */
  16. if ($previousDateInArray != $dayBeforeDate) {
  17. if ($tempDateRange !== $dates[$index-1]) {
  18. $tempDateRange .= ' to ' . $dates[$index-1];
  19. }
  20. /*
  21. Store the previous tempValue and start a new temptative dateRange
  22. */
  23. $result[] = $tempDateRange;
  24. $tempDateRange = $date ;
  25. }
  26. } else {
  27. $tempDateRange = $date ;
  28. }
  29. } // end foreach
  30. /*
  31. Finish processing the last date
  32. */
  33. if ($tempDateRange !== $date) {
  34. $tempDateRange .= ' to ' . $dates[$index];
  35. } else {
  36. $tempDateRange = $date ;
  37. }
  38.  
  39. $result[] = $tempDateRange;
  40. return $result;
  41. }
  42. $dates=array('1973-10-16','1973-10-17','1973-10-18','1973-10-19','1973-10-22');
  43. <pre>';
  44. print_r($dates);
  45.  
  46. $dateRanges = detectDateRanges($dates);
  47.  
  48. print_r($dateRanges);