Search code examples
phplaravellaravel-5php-carbon

Get an array of dates using Carbon in Laravel 5.4


I'm a beginner in Laravel/PHP, and I'm using the Carbon class to manage dates. I need to get an array of datetime by month, from the beginning of the previous year till this month, the output should be as follow :

$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',
];

I can't figure out how to do this, thank you in advance.


Solution

  • Maybe something like this:

    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;
    }