5

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
Alive to die - Anant
  • 70,531
  • 10
  • 51
  • 98
Sarath TS
  • 2,432
  • 6
  • 32
  • 79

2 Answers2

5

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);
}
Max
  • 891
  • 8
  • 17
3

You can use for loop to achieve such type of result. Your requirement is to print date in one day difference between start and end date. I have write code for this .

<?php
$startDate = strtotime('2016-11-01 10:00:00');
$endDate = strtotime('2016-11-03 18:00:00');

for ($loopStart = $startDate; $loopStart <= $endDate; $loopStart = strtotime('+1 day', $loopStart)) {

    // check last date
    if($endDate >= strtotime('+1 day', $loopStart)){
      echo  date('Y-m-d', $loopStart).' 23:59:59';
    }
    else{
      echo  date('Y-m-d', $loopStart).' '.date('H:i:s',$endDate);
    }

    echo "<br>";

}

?>

The output of the code is -

2016-11-01 23:59:59
2016-11-02 23:59:59
2016-11-03 18:00:00
Prakash Saini
  • 481
  • 3
  • 11
  • 1
    If i added `$startDate = strtotime('2016-11-28 07:58:18'); $endDate = strtotime('2016-11-29 07:58:18'); ` The result I am getting is `2016-11-28 07:58:18
    2016-11-29 07:58:18
    `. In this case this is not correct.
    – Sarath TS Nov 28 '16 at 09:34
  • For this case we need to update the >= in if statement. Just update the if conditions as if($endDate >= strtotime('+1 day', $loopStart)){ – Prakash Saini Nov 28 '16 at 09:58