目前尚不清楚通过“间隔”您是否真的想要一个DateInterval
对象,或者可能DateTime
每天都有一个单独的开始/结束。无论哪种方式,下面应该作为一个明智的出发点。
<?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 \n",
$date_start->format('Y-m-d H:i'),
$date_end->format('Y-m-d H:i')
);
}
产生以下输出:
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
附录
如果您足够幸运能够使用 PHP 5.5.0 或更高版本,那么DateTimeImmutable
该类将使克隆/修改部分更加整洁。