Zaffar Saffee Zaffar Saffee - 5 months ago 11
PHP Question

PHP DateTime and Interval unexpected behavior

here is my code (using 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);
}


expected output would be (atleast for me)

05-01-2016
05-02-2016


it actually gives me

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


I cant understand it... any help is appreciated

here is output
enter image description here

Answer

You set 59 hour :) - It is more than two days. Now your end datetime is Thu, 05 May 2016 11:59:59

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

Set 23 hours and it will work

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