Search code examples
phplaravelphp-carbon

Carbon get quarter of the year


I want to get my data quarter based so for each year I will have 4 variable like pastYearsQOne pastYearsQTwo pastYearsQThree pastYearsQFour.

My question is how can I get quarters of the year?

code

$pastYearsQOne = Project::orderby('id', 'desc')->whereDate(
  'created_at', '<=', now()->subYear(1)->startOfQuarter()->toDateTimeString()
                                         ^^^^^^^^^^^^^^^^
)->count();

If still didn't get it! here is the logic,

Final result will be like:

$pastYearsQOne = data of: 2020 (year) -> 01~03 (months)

$pastYearsQTwo = data of: 2020 (year) -> 04~06 (months)

$pastYearsQThree = data of: 2020 (year) -> 07~09 (months)

$pastYearsQFour = data of: 2020 (year) -> 10~12 (months)

Solution

  • startOfQuarter and endOfQuarter quarter are useful, along with month function.

    Please try using the below code.

    $startOfQ1 = Carbon::now()->subYear()->month(1)->startOfQuarter();
    $endOfQ1 = Carbon::now()->subYear()->month(1)->endOfQuarter();
    
    $startOfQ2 = Carbon::now()->subYear()->month(4)->startOfQuarter();
    $endOfQ2 = Carbon::now()->subYear()->month(4)->endOfQuarter();
    
    $startOfQ3 = Carbon::now()->subYear()->month(7)->startOfQuarter();
    $endOfQ3 = Carbon::now()->subYear()->month(7)->endOfQuarter();
    
    $startOfQ4 = Carbon::now()->subYear()->month(10)->startOfQuarter();
    $endOfQ4 = Carbon::now()->subYear()->month(10)->endOfQuarter();