0

I have a date range in which I want to process between each day. So for example between 2013-03-01 00:00:00 and 2013-04-01 00:00:00 there are 31 days

so my for loop is something like this

$date_next = $date_from;
for($i=0;$i<31-1;$i++)
{
    $date_next_str = new DateTime($date_next);
    $date_next_1_str = new DateTIme($date_next);
    $date_next_1_str->modify("+1 day");
    $date_next_1_str->modify("-1 second");

    $date_next_1_str->modify("+1 day");
    $date_next = $date_next_1_str->date;
}

so in my first loop it will be from 2013-03-01 00:00:00 to 2013-03-01 23:59:59

However when I assign $date_next_1_str->date to $date_next at the end of the for loop, the $date_next still shows 2013-03-01 23:59:59, which was supposed to be 2013-03-02 00:00:00.

Anyone can help me with this? Thanks in advance!

4

1 回答 1

0

你可以很容易地使用 PHP 的DateTimeDateIntervalDatePeriod对象来做到这一点:-

$startDate = \DateTime::createFromFormat('Y-m-d H:i:s', '2013-03-01 00:00:00');
$endDate = \DateTime::createFromFormat('Y-m-d H:i:s', '2013-04-01 00:00:00');
$interval = new \DateInterval('P1D');
$endDate->add($interval); //As otherwise last day will be missed off.
$period = new \DatePeriod($startDate, $interval, $endDate);

foreach($period as $date){
    //each $date is an instance of DateTime
    var_dump($date); // Or whatever you want to do with the DateTime object
}
于 2013-04-14T16:14:25.433 回答