DatePeriod类输出问题

时间:2017-09-06 13:22:28

标签: php datetime

我使用DatePeriod来获取两个日期之间的日期差异,但是当我需要获取基于数据Year的格式时会产生问题。以下是我的工作

$start_date = '2016-08-29 21:47:33';
$end_date = '2018-04-28 17:30:55';

function getDateRange($start_date, $end_date, $type, $format = 'Y-m-d')
{
    $period = new DatePeriod(
        new DateTime($start_date),
        new DateInterval("P1{$type}"),
        new DateTime($end_date)
    );

    $dates = [];

    foreach($period as $dt)
    {
        $dates[] = $dt->format("$format");
    }

    return $dates;
}

print_r(getDateRange($start_date, $end_date, 'Y', 'Y'));

根据我的功能,它应该返回

Array
(
    [0] => 2016
    [1] => 2017
    [2] => 2018
)

但它只输出了两个

Array
(
    [0] => 2016
    [1] => 2017
)

如果我使用Month & Year的输出格式,M Y interval Month,那么它的输出效果很好

print_r(getDateRange($start_date, $end_date, 'M', 'M Y'));

Array
(
    [0] => Aug 2016
    [1] => Sep 2016
    [2] => Oct 2016
    [3] => Nov 2016
    [4] => Dec 2016
    [5] => Jan 2017
    [6] => Mar 2017
    [7] => Apr 2017
    [8] => May 2017
    [9] => Jun 2017
    [10] => Jul 2017
    [11] => Aug 2017
    [12] => Sep 2017
    [13] => Oct 2017
    [14] => Nov 2017
    [15] => Dec 2017
    [16] => Jan 2018
    [17] => Feb 2018
    [18] => Mar 2018
    [19] => Apr 2018
)

2 个答案:

答案 0 :(得分:3)

我已根据文档link

修改了更改

这是代码,

function getDateRange($start_date, $end_date, $type, $format = 'Y-m-d')
{
    $start_date = date_create_from_format("Y-m-d H:i:s", $start_date);
    $end_date = date_create_from_format("Y-m-d H:i:s", $end_date);
    $endDateInt = new DateInterval( "P1Y" );
    $end_date->add( $endDateInt );
    $period = new DatePeriod(
        $start_date,
        new DateInterval("P1{$type}"),
        $end_date
    );
    $dates = [];

    foreach($period as $dt)
    {
        $dates[] = $dt->format("$format");
    }

    return $dates;
}
$start_date = '2016-08-29 21:47:33';
$end_date = '2018-04-28 17:30:55';
print_r(getDateRange($start_date, $end_date, 'Y', 'Y'));

以下是link

答案 1 :(得分:2)

您可以在第二个输出中看到原因。最后一个日期只到4月,第一个日期是8月。所以它确实不是两整年,你的第一个结果是正确的。如果你想让它成为"年的数量",而不考虑实际的差异,你可以通过将第二个日期设置为同一天和月来模拟这个。第一个,如果$type是Y:

<?php
$start_date = '2016-08-29 23:47:33';
$end_date = '2018-09-28 17:30:55';

function getDateRange($start_date, $end_date, $type, $format = 'Y-m-d')
{
    $start = new DateTime($start_date);
    $end = new DateTime($end_date);
    if ($type === "Y") {
        $start->setTime(0, 0, 0);
        $end->setDate($end->format("Y"), $start->format("m"), $start->format("d"));
        $end->setTime(0, 0, 1);
    }
    $period = new DatePeriod(
        $start,
        new DateInterval("P1{$type}"),
        $end
    );

    $dates = [];

    foreach($period as $dt)
    {
        $dates[] = $dt->format("$format");
    }

    return $dates;
}

print_r(getDateRange($start_date, $end_date, 'Y', 'Y'));

Demo