Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can we split dates in php?

Tags:

php

How can we split dates using PHP? Is there any built in function in PHP?

2016-11-01 10:00:00 till 2016-11-03 18:00:00

I need to split above date in to required dates:-

2016-11-01 10:00:00 till 23:59:59
2016-11-02 00:00:00 till 23:59:59
2016-11-03 00:00:00 till 18:00:00
like image 795
Sarath TS Avatar asked Nov 28 '16 08:11

Sarath TS


1 Answers

To my knowledge PHP does not provide such built-in feature.

But you can easily achieve this with th DateTime object :

$interval = '2016-11-01 10:00:00 till 2016-11-03 18:00:00';
$dates = explode(' till ', $interval);

if(count($dates) == 2) {
    $current = $begin = new DateTime($dates[0]);
    $end = new DateTime($dates[1]);

    $intervals = [];

    // While more than 1 day remains
    while($current->diff($end)->format('%a') >= 1) {

        $nextDay = clone $current;
        $nextDay->setTime(23,59,59);

        $intervals []= [
            'begin' => $current->format('Y-m-d H:i:s'),
            'end'   => $nextDay->format('Y-m-d H:i:s'),
        ];
        $current = clone $nextDay;
        $current->setTime(0,0,0);
        $current->modify('+1 day');
    }

    // Last interval : from $current to $end
    $intervals []= [
        'begin' => $current->format('Y-m-d H:i:s'),
        'end'   => $end->format('Y-m-d H:i:s'),
    ];

    print_r($intervals);
}
like image 85
Max Avatar answered Oct 31 '22 03:10

Max