Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

date

raku

quarter

Given a date, return the date of the last day of the quarter preceding the quarter in which this date falls. for example

2020-04-25 => 2020-03-31
2020-06-25 => 2020-03-31
2020-09-25 => 2020-06-30
2020-10-25 => 2020-09-30

if the given date is in the first quarter, the year minus 1

2020-03-25 => 2019-12-31
like image 318
chenyf Avatar asked Jul 25 '20 02:07

chenyf


2 Answers

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.

like image 181
Elizabeth Mattijsen Avatar answered Oct 31 '22 14:10

Elizabeth Mattijsen


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
like image 36
chenyf Avatar answered Oct 31 '22 14:10

chenyf