How can we split dates in php?

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

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

I need to split the date above into the desired 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 
+5
source share
2 answers

To my knowledge, PHP does not provide such a built-in function.

But you can easily achieve this with a 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('Ymd H:i:s'), 'end' => $nextDay->format('Ymd 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('Ymd H:i:s'), 'end' => $end->format('Ymd H:i:s'), ]; print_r($intervals); } 
+5
source

You can use to cycle to achieve this result. Your requirement is to print the date one day apart between the start and end dates. I have a 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('Ym-d', $loopStart).' 23:59:59'; } else{ echo date('Ym-d', $loopStart).' '.date('H:i:s',$endDate); } echo "<br>"; } ?> 

Output Code -

 2016-11-01 23:59:59 2016-11-02 23:59:59 2016-11-03 18:00:00 
+3
source

Source: https://habr.com/ru/post/1260439/


All Articles