skip to Main Content

I have a time interval which consists of two DateTimes:

array(
    "DATE_TIME_FROM" => new DateTime(...) , //2021-01-01 10:00
    "DATE_TIME_TO" => new DateTime(...), //2021-01-02 01:00
) 

If any of these datetimes go beyound the day then an existing array should be split into two like I shown in an example below:

array(
    "DATE_TIME_FROM" => new DateTime(...) , //2021-01-01 10:00
    "DATE_TIME_TO" => new DateTime(...), //2021-01-02 00:00
), 
array(
    "DATE_TIME_FROM" => new DateTime(...) , //2021-01-02 00:00
    "DATE_TIME_TO" => new DateTime(...), //2021-01-02 01:00
) 

Is it possible somehow? Thanks in advance!

2

Answers


  1. You can iterate through a DatePeriod with a DateInterval of 1 day from start DateTime to end DateTime:

    function splitDates(DateTime $start, DateTime $end) : array {
        $start_datetime = clone $start;
        $end_datetime = clone $end;
        $start_datetime->setTime(0, 0, 0, 0);
        $end_datetime->setTime(23, 59, 59, 999999);
        $end_datetime->modify('+1 microsecond');
        $interval = new DateInterval('P1D');
        $daterange = new DatePeriod($start_datetime, $interval ,$end_datetime);
        $resultset = [];
        foreach($daterange as $key=>$date) {
            $end_datetime = clone $date;
            $end_datetime->setTime(23, 59, 59, 999999);
            $end_datetime->modify('+1 microsecond');
            $resultset[] = [
                'start' => $date,
                'end'   => $end_datetime,
            ];
        }
        $resultset[0]['start'] = $start;
        $resultset[array_key_last($resultset)]['end'] = $end;
        return $resultset;
    }
    
    
    $results = splitDates(new DateTime('2021-01-01 10:00:00'), new DateTime('2021-01-04 01:00:00'));
    var_dump($results);
    
    Login or Signup to reply.
  2. Get the midnight of DATE_TIME_TO:

    $midnight = clone $arr['DATE_TIME_TO'];
    $midnight->modify('midnight');
    

    If it is greater than DATE_TIME_FROM, split the array into two:

    if($midnight > $arr['DATE_TIME_FROM'])
        $arr = [
            [
                'DATE_TIME_FROM' => $arr['DATE_TIME_FROM'],
                'DATE_TIME_TO' => $midnight
            ],
            [
                'DATE_TIME_FROM' => $midnight,
                'DATE_TIME_TO' => $arr['DATE_TIME_TO']
            ]
        ];
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search