Skip to content
Browse files

[core/Temporal.pm] implemented Date.delta

  • Loading branch information...
1 parent 7e10a0d commit b49cbe0a8d8870309ef2a0d7f39cfdae6e83878d @masak masak committed Jan 24, 2013
Showing with 38 additions and 0 deletions.
  1. +6 −0 src/core/Exception.pm
  2. +32 −0 src/core/Temporal.pm
View
6 src/core/Exception.pm
@@ -1125,6 +1125,12 @@ my class X::DateTime::TimezoneClash does X::Temporal {
'DateTime.new(Str): :timezone argument not allowed with a timestamp offset';
}
}
+my class X::DateTime::InvalidDeltaUnit does X::Temporal {
+ has $.unit;
+ method message() {
+ "Cannnot use unit $.unit with Date.delta";
+ }
+}
my class X::Eval::NoSuchLang is Exception {
has $.lang;
View
32 src/core/Temporal.pm
@@ -546,6 +546,38 @@ my class Date does Dateish {
self.clone(|self.truncate-parts($unit));
}
+ method delta($amount, TimeUnit $unit) {
+ my $date;
+
+ given $unit {
+ X::DateTime::InvalidDeltaUnit.new(:$unit).throw
+ when second | seconds | minute | minutes | hour | hours;
+
+ my $day-delta;
+ when day | days { $day-delta = $amount; proceed }
+ when week | weeks { $day-delta = 7 * $amount; proceed }
+
+ when month | months {
+ my ($month, $year) = $!month, $!year;
+ $month += $amount;
+ $year += floor(($month - 1) / 12);
+ $month = ($month - 1) % 12 + 1;
+ $date = Date.new(:$year, :$month, :$!day);
+ succeed;
+ }
+
+ when year | years {
+ my $year = $!year + $amount;
+ $date = Date.new(:$year, :$!month, :$!day);
+ succeed;
+ }
+
+ $date = Date.new-from-daycount(self.daycount + $day-delta);
+ }
+
+ $date;
+ }
+
method clone(*%_) {
my %args = { :$!year, :$!month, :$!day, %_ };
self.new(|%args);

0 comments on commit b49cbe0

Please sign in to comment.
Something went wrong with that request. Please try again.