Concatenate consecutive dates in date strings
P粉946336138
P粉946336138 2024-02-04 08:58:08
0
1
494

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粉946336138
P粉946336138

reply all(1)
P粉057869348

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);
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template