Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
[core/Temporal.pm] implemented Date.delta
  • Loading branch information
Carl Masak committed Jan 24, 2013
1 parent 7e10a0d commit b49cbe0
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 0 deletions.
6 changes: 6 additions & 0 deletions src/core/Exception.pm
Expand Up @@ -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;
Expand Down
32 changes: 32 additions & 0 deletions src/core/Temporal.pm
Expand Up @@ -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);
Expand Down

0 comments on commit b49cbe0

Please sign in to comment.