Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel using carbon to get current quarter

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.

like image 354
imperium2335 Avatar asked Apr 06 '15 14:04

imperium2335


3 Answers

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();
like image 92
user1669496 Avatar answered Nov 14 '22 21:11

user1669496


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.

like image 28
imperium2335 Avatar answered Nov 14 '22 21:11

imperium2335


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 */
like image 40
Phantom1412 Avatar answered Nov 14 '22 21:11

Phantom1412