search

Home  >  Q&A  >  body text

Concatenate consecutive dates in date strings

I have a string with dates separated by commas and I want to calculate if any single dates are connected.

So the list might be:

2022-07-15, 2022-07-16, 2022-07-17, 2022-07-18, 2022-07-22, 2022-07-25, 2022-07-26, 2022-07-27, 2022-07-28

What I want to achieve is that I get the interval of "concatenated" dates and then "individually" get the "single" date like this:

0 => 2022-07-15 - 2022-07-18
1 => 2022-07-22
2 => 2022-07-25 - 2022-07-28

Is it possible to calculate from a string to the output with some explosions and looping through the dates somehow?

P粉946336138P粉946336138295 days ago501

reply all(1)I'll reply

  • P粉057869348

    P粉0578693482024-02-05 00:58:06

    Yes, you can:

    • Decompose the string into date string parts
    • Sort the list. Given that the format is YYYY-MM-DD, the default lexical ordering is fine.
    • Iterate over list and grouped entries in subarrays when they represent consecutive dates. Use strtotime($date . ' 1 day') to calculate the next date and verify that the next date in the sorted array matches it. If it matches the expected date, make it the second entry in the current subarray. If there is no match, start a new subarray,...etc
    • Finally convert these subarrays into the string format you need.
    function groupDates($input) {
        $arr = explode(", ", $input);
        sort($arr);
        $expected = -1;
        foreach ($arr as $date) {
            if (strtotime($date) == $expected) {
                array_splice($range, 1, 1, $date);
            } else {
                unset($range);
                $range = [$date];
                $ranges[] = &$range;
            }
            $expected = strtotime($date . ' + 1 day');
        }
        foreach ($ranges as $entry) {
            $result[] = implode(" - ", $entry);
        }
        return $result;
    }
    
    // Demo run
    $str = "2022-07-15, 2022-07-16, 2022-07-17, 2022-07-18, 2022-07-22, 2022-07-25, 2022-07-26, 2022-07-27, 2022-07-28";
    $result = groupDates($str);
    print_r($result);

    reply
    0
  • Cancelreply