Laravel using carbon to get current quarter
11,608
Solution 1
You can use the firstOfQuarter
and lastOfQuarter
methods for determining the beginning and end dates of a quarter...
$date = new \Carbon\Carbon('-3 months');
$firstOfQuarter = $date->firstOfQuarter();
$lastOfQuarter = $date->lastOfQuarter();
Solution 2
I think I have solved it:
...
case 9:
$a = Carbon::now();
$a->month($a->month-3);
$lastQuarter = $a->quarter;
$query->where(DB::raw('QUARTER(FT.created_at)'), $lastQuarter);
$query->where(DB::raw('YEAR(FT.created_at)'), $a->year);
break;
...
Please let me know a nicer way to do this if there is one, your help is much appreciated.
Solution 3
Just to add more to the answer above, the actual methods that should be use is the following methods:
$date = new \Carbon\Carbon('-3 months'); // for the last quarter requirement
$date->startOfQuarter(); // the actual start of quarter method
$date->endOfQuarter(); // the actual end of quarter method (with time 23:59:59.999999)
the following are not exactly correct:
$date->firstOfQuarter(); /* use this method when you wish to get the first
occurrence of a given day in the current quarter, its
fallback works similar to the startOfQuarter() method */
$date->lastOfQuarter(); /* this is where the problem located, unlike the
endOfQuarter() method, this method return the start of a
day (with time 00:00:00.000000) (because the method is
designed to get the last occurrence of a given day in the
current quarter */
Comments
-
imperium2335 almost 2 years
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.
I tried the intuitive
echo new Carbon('this quarter');
way which doesn't work, but I guess they don't have one for quarters.
I figured it out, I did:
$query->where(DB::raw('QUARTER(FT.created_at)'), Carbon::now()->quarter); $query->where(DB::raw('YEAR(FT.created_at)'), '=', Carbon::now()->year);
But now I am struggling with how to get the start and end date of the last quarter.