I am posting a start date and time, and an end date and time , for example:
$_POST['start_date'] //this might be 27:04:2013
$_POST['start_time'] //this might be 16:30
$_POST['end_date'] //this might be 29:04:2013
$_POST['end_time'] //this might equal 22:30
I want to create an array of objects for each day that the posted interval of time stretches, would this be a DateInterval object? if so then in the above posted values i want to get an array with the following
[0] 27:04:2013 16:30:00 27:04:2013 23:59:59
[1] 28 04:2014 00:00:00 28 04:2014 23:59:59
[2] 29:04:2014 00:00:00 29:04:2014 22:30:00
$start = DateTime::createFromFormat('d:m:Y H:i', '27:04:2013 16:30');
$end = DateTime::createFromFormat('d:m:Y H:i', '29:04:2013 22:30');
$diff = $start->diff($end);
$pad = ($start->format('His') > $end->format('His')) ? 2 : 1;
$days = $diff->d + $pad;
for ($i = 1; $i <= $days; $i++) {
if ($i === 1) {
printf("%s %s<br>", $start->format('d:m:Y H:i:s'), $start->format('d:m:Y 23:59:59'));
}
else if ($i === $days) {
printf("%s %s<br>", $end->format('d:m:Y 00:00:00'), $end->format('d:m:Y H:i:s'));
}
else {
printf("%s %s<br>", $start->format('d:m:Y 00:00:00'), $start->format('d:m:Y 23:59:59'));
}
$start->modify('+1 day');
}
It is not clear whether by "interval" you really want a DateInterval
object or perhaps a separate start/end DateTime
for each day. Either way, the below should serve as a sensible point to go from.
<?php
$start_date = '27:04:2013';
$start_time = '16:30';
$end_date = '29:04:2013';
$end_time = '22:30';
// Date input strings and generate a suitable DatePeriod
$start = DateTime::createFromFormat("d:m:Y H:i", "$start_date $start_time");
$end = DateTime::createFromFormat("d:m:Y H:i", "$end_date $end_time");
$interval = new DateInterval('P1D');
$period = new DatePeriod($start, $interval, $end);
foreach ($period as $date) {
// Get midnight at start of current day
$date_start = clone $date;
$date_start->modify('midnight');
// Get 23:59:59, end of current day
// (moving to midnight of next day might be good too)
$date_end = clone $date;
$date_end->modify('23:59:59');
// Take care of partial days
$date_start = max($start, $date_start);
$date_end = min($end, $date_end);
// Here you would construct your array of
// DateTime pairs, or DateIntervals, as you want.
printf(
"%s -> %s
",
$date_start->format('Y-m-d H:i'),
$date_end->format('Y-m-d H:i')
);
}
Which produces the following output:
2013-04-27 16:30 -> 2013-04-27 23:59
2013-04-28 00:00 -> 2013-04-28 23:59
2013-04-29 00:00 -> 2013-04-29 22:30
Addendum
If you're lucky enough to be able to use PHP 5.5.0 or above, then the DateTimeImmutable
class would make the clone/modify parts much tidier.