php DatePeriod对象访问开始日期和当前日期


php DatePeriod Object access start and current date

我的理解是,您无法访问日期期间对象的开始日期和当前日期。我目前的php是5.5,有没有解决办法,因为我无法升级到php 5.6或php 7,我需要获得这些日期。

DatePeriod Object
(
    [start] => DateTime Object
        (
            [date] => 2016-04-03 00:00:00
            [timezone_type] => 3
            [timezone] => UTC
        )
    [current] => DateTime Object
        (
            [date] => 2016-04-10 00:00:00
            [timezone_type] => 3
            [timezone] => UTC
        )
)

DatePeriod是一个Traversable接口实现。它只支持foreach循环。

您只能将开始元素和当前元素转换为数组:

$start    = new DateTime( '2016-03-01' );
$end      = new DateTime( '2016-03-31' );
$interval = new DateInterval( 'P1D' );
$period   = new DatePeriod( $start, $interval ,$end );
$arPeriod = iterator_to_array( $period );
$startDate   = $arPeriod[0];
next( $arPeriod );
$currentDate = current( $arPeriod );