0

I need to return date time start and date time end for each date in a given range:

The input would be:

$start = '2010-11-07 10:00:00';
$end   = '2010-11-09 19:00:00';

The expected output would be:

Array
(
    Array
        (
            '2010-11-07',
            '2010-11-07 10:00:00' ,
            '2010-11-08 00:00:00'
        )

    Array
        (
            '2010-11-08' ,            
            '2010-11-08 00:00:00' ,
            '2010-11-09 00:00:00'
        )

    Array
        (
            '2010-11-09' ,
            '2010-11-09 00:00:00' ,
            '2010-11-09 19:00:00'
        )

)

I managed to divide the time range into separate days using this thread: https://stackoverflow.com/a/4312630/3132858

However, I cannot get the start and end time for each date. Any help will be appreciated!

Here is a PHP Fiddle with my code.

user3132858
  • 609
  • 1
  • 11
  • 27

1 Answers1

1

One way to solve this is to simply loop through the days between the start/end dates:

function getRange($start, $end) {
    $range = [];
    $start_date = \DateTime::createFromFormat('Y-m-d H:i:s', $start);
    $end_date = \DateTime::createFromFormat('Y-m-d H:i:s', $end);
    $diff = $end_date->diff($start_date);
    for($i = 0; $i <= $diff->days; $i++) {
        $event_end = clone $start_date;
        $event_end->add(new \DateInterval("P1D"));
        if ($event_end > $end_date) {
            $range[] = [
                $start_date->format('Y-m-d'),
                $start_date->format('Y-m-d 00:00:00'),
                $end_date->format('Y-m-d H:i:s'),
            ];
            break;
        }
        $range[] = [
            $start_date->format('Y-m-d'),
            $i > 0 ? $start_date->format('Y-m-d 00:00:00') :  $start_date->format('Y-m-d H:i:s'),
            $event_end->format('Y-m-d 00:00:00')

        ];
        $start_date->add(new \DateInterval("P1D"));
    }
    return $range;
}

See it running here: https://3v4l.org/e85OM

mrbm
  • 2,164
  • 12
  • 11
  • Wow excellent job, code works just perfect! Thank you very much, you really helped a lot! – user3132858 Nov 25 '19 at 21:06
  • Actually, just noticed if the range is like this: `'2010-11-07 10:00:00', '2010-11-07 19:00:00'`, the function returns `"2010-11-07", "2010-11-07 00:00:00", "2010-11-07 19:00:00"` instead of `"2010-11-07", "2010-11-07 10:00:00", "2010-11-07 19:00:00"` instead of – user3132858 Nov 25 '19 at 21:19