Search code examples
laraveldatephp-carbon

How to find quarter first date and last date from current date using laravel


I am trying to set a start date and end date by the current quarter.

        case 'quarter':
            $date =  Carbon::now()->month(Carbon::now()->month-3);
            print_r($date);
            $startDate = Carbon::now()->startOfQuarter(); // the actual start of quarter method
            $endDate = Carbon::now()->endOfQuarter();
        break;

output as

quarter
Carbon\Carbon Object
(
[date] => 2020-12-04 05:21:08.443008
[timezone_type] => 3
[timezone] => UTC
)
Array
(
[startDate] => Carbon\Carbon Object
(
[date] => 2021-01-01 00:00:00.000000
[timezone_type] => 3
[timezone] => UTC
)

[endDate] => Carbon\Carbon Object
(
[date] => 2021-03-31 23:59:59.999999
[timezone_type] => 3
[timezone] => UTC
)

)

How can I use Carbon to determine the current quarter? I.e. I would like to get hold of the date when the quarter started and the date when it ends. and also I am trying to set a start date and end date by the previous quarter.

 case 'quarter':
            $date =  Carbon::now()->month(Carbon::now()->month-6);            
            $startDate = Carbon::now()->startOfQuarter(); // the actual start of quarter method
            $endDate = Carbon::now()->endOfQuarter();
        break;

But now I am struggling with how to get the start and end date of the current quarter and previous quarter.


Solution

  • $date = CarbonImmutable::now();
    $startCurrent = $date->startOfQuarter();
    $startPrevious = $startCurrent->subQuarter();
    
    echo $startPrevious . "\n";
    echo $startPrevious->endOfQuarter() . "\n";
    echo $startCurrent . "\n";
    echo $startCurrent->endOfQuarter() . "\n";