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
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With