使用Laravel 5.4中的Carbon获取一系列日期

时间:2017-08-30 19:13:53

标签: php laravel laravel-5 php-carbon

我是Laravel / PHP的初学者,我使用Carbon类来管理日期。 我需要按月从上一年的开始到本月获得一系列日期时间,输出应如下:

$dates = [
    '2016-01-01 00:00:00',
    '2016-02-01 00:00:00',
    '2016-03-01 00:00:00',
    '2016-04-01 00:00:00',
    '2016-05-01 00:00:00',
    '2016-06-01 00:00:00',
    '2016-07-01 00:00:00',
    '2016-08-01 00:00:00',
    '2016-09-01 00:00:00',
    '2016-10-01 00:00:00',
    '2016-11-01 00:00:00',
    '2016-12-01 00:00:00',
    '2017-01-01 00:00:00',
    '2017-02-01 00:00:00',
    '2017-03-01 00:00:00',
    '2017-04-01 00:00:00',
    '2017-05-01 00:00:00',
    '2017-06-01 00:00:00',
    '2017-07-01 00:00:00',
    '2017-08-01 00:00:00',
];

我无法弄清楚如何做到这一点,谢谢你。

1 个答案:

答案 0 :(得分:0)

也许是这样的:

function dates()
{
    $start = \Carbon\Carbon::now()->subYear()->startOfYear();
    $months_to_render = \Carbon\Carbon::now()->diffInMonths($start);

    $dates = [];

    for ($i = 0; $i <= $months_to_render; $i++) {
        $dates[] = $start->toDateTimeString();
        $start->addMonth();
    }

    return $dates;
}