Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    New to the CF scene
    Join Date
    Nov 2008
    Posts
    6
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Displaying a date range from an array of dates

    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.

  • #2
    New to the CF scene
    Join Date
    Nov 2008
    Posts
    6
    Thanks
    2
    Thanked 0 Times in 0 Posts
    5 minutes after posting this I found this:

    PHP Code:
    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...ries-of-dates/

    Problem solved


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •