Skip to content

Commit

Permalink
Add Date/DateTime.dd-mm-yyyy / mm-dd-yyyy methods
Browse files Browse the repository at this point in the history
Seeing the code from https://covid.observer made me realize that
most uses of the formatter for Date/DateTime is to create the
mm-dd-yyyy and dd-mm-yyyy alternatives for dates.  Since these
methods would be 250x faster than using a sprintf and the formatter,
it seems like a good thing to add, especially since these methods
allow for a different separator so today would can show up for our
American friends as:

    say Date.today.mm-dd-yyyy("/");  # 03/14/2020
  • Loading branch information
lizmat committed Mar 14, 2020
1 parent 3017cfe commit 70ac9b7
Showing 1 changed file with 34 additions and 0 deletions.
34 changes: 34 additions & 0 deletions src/core.c/Dateish.pm6
Expand Up @@ -149,6 +149,40 @@ my role Dateish {
nqp::join($sep,$parts)
}

method dd-mm-yyyy(str $sep = "-" --> Str:D) {
my $parts := nqp::list_s;
nqp::push_s($parts, $!day < 10
?? nqp::concat('0',$!day)
!! nqp::tostr_I(nqp::getattr_i(self,$?CLASS,'$!day'))
);
nqp::push_s($parts, $!month < 10
?? nqp::concat('0',$!month)
!! nqp::tostr_I(nqp::getattr_i(self,$?CLASS,'$!month'))
);
nqp::push_s($parts, $!year < 1000 || $!year > 9999
?? self!year-Str
!! nqp::tostr_I(nqp::getattr_i(self,$?CLASS,'$!year'))
);
nqp::join($sep,$parts)
}

method mm-dd-yyyy(str $sep = "-" --> Str:D) {
my $parts := nqp::list_s;
nqp::push_s($parts, $!month < 10
?? nqp::concat('0',$!month)
!! nqp::tostr_I(nqp::getattr_i(self,$?CLASS,'$!month'))
);
nqp::push_s($parts, $!day < 10
?? nqp::concat('0',$!day)
!! nqp::tostr_I(nqp::getattr_i(self,$?CLASS,'$!day'))
);
nqp::push_s($parts, $!year < 1000 || $!year > 9999
?? self!year-Str
!! nqp::tostr_I(nqp::getattr_i(self,$?CLASS,'$!year'))
);
nqp::join($sep,$parts)
}

method earlier(*%unit) { self.later(:earlier, |%unit) }

method !truncate-ymd(Cool:D $unit, %parts? is copy) {
Expand Down

0 comments on commit 70ac9b7

Please sign in to comment.