PHP DateTime和Interval意外行为

时间:2016-06-09 20:29:59

标签: php loops date datetime foreach

这是我的代码(使用laravel)

$start = '05-01-2016';
$end = '05-03-2016';
$start_date = new Carbon;
$end_date = new Carbon;
$format = 'm-d-Y';
$begin = Carbon::createFromFormat($format, $start);
$begin->setTime(0, 0, 0);
$end = Carbon::createFromFormat($format, $end);
$end->setTime(59, 59, 59);
//dd($begin,$end);
$interval = new \DateInterval('P1D');
$dateRange = new \DatePeriod($begin, $interval, $end);
foreach ($dateRange as $date) {
    $start_time = $start_date->setDateTime($date->format("Y"), $date->format("m"), $date->format("d"), 0, 0, 0)->toDateTimeString();
    $end_time =$end_date->setDateTime($date->format("Y"), $date->format("m"), $date->format("d"), 23, 59, 59)->toDateTimeString();
    var_dump($start_time);
    //var_dump($end_time);
}

预计的输出将是(至少对我而言)

05-01-2016
05-02-2016

它实际上给了我

05-01-2016
05-02-2016
05-03-2016
05-04-2016
05-05-2016

我无法理解......感谢任何帮助

这是输出 enter image description here

1 个答案:

答案 0 :(得分:1)

你设置59小时:) - 这是超过两天。现在您的结束日期时间为Thu, 05 May 2016 11:59:59

$end->setTime(59, 59, 59);

设置23小时,它将起作用

$end->setTime(23, 59, 59);