Get the date of the last day of the quarter preceding the quarter in which this date falls

sub MAIN(Date(Str) $date) {
    say $date.earlier(months => ($date.month - 1) % 3 + 1).last-date-in-month
}

This requires at least Rakudo 2020.05.


sub MAIN(Str $day) {
    my Date $d       = Date.new($day);
    my Int  $year    = $d.year;
    my Int  $month   = $d.month;
    my Int  $quarter = ($month/3).ceiling; # the quarter that this date falls

    my @last-days = ('12-31', '03-31', '06-30', '09-30');

    # if the given date is in the first quarter, then `$year` minus 1
    $year-=1 if $quarter == 1; 

    say sprintf('%s-%s', $year, @last-days[$quarter-1]);
 }

save the above code as quarter.raku, the output is:

$ raku quarter.raku 2020-03-25
2019-12-31
 
$ raku quarter.p6 2020-04-25
2020-03-31
 
$ raku quarter.p6 2020-06-25
2020-03-31
 
$ raku quarter.p6 2020-07-25
2020-06-30

$ raku quarter.p6 2020-08-25
2020-06-30
 
$ raku quarter.p6 2020-09-25
2020-06-30
 
$ raku quarter.p6 2020-10-25
2020-09-30

Tags:

Date

Raku

Quarter