Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add method: add_days #66

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 12 additions & 3 deletions Piece.pm
Original file line number Diff line number Diff line change
Expand Up @@ -715,6 +715,14 @@ sub compare {
return $lhs <=> $rhs;
}

sub add_days {
my ($time, $num_days) = @_;

croak("add_days requires a number of days") unless defined($num_days);

return add($time, $num_days * ONE_DAY);
}

sub add_months {
my ($time, $num_months) = @_;

Expand Down Expand Up @@ -1029,13 +1037,14 @@ while examining the object will print the number of seconds (because
of the overloading), you can also get the number of minutes, hours,
days, weeks and years in that delta, using the Time::Seconds API.

In addition to adding seconds, there are two APIs for adding months and
years:
In addition to adding seconds, there are three APIs for adding days,
months and years:

$t = $t->add_days(7);
$t = $t->add_months(6);
$t = $t->add_years(5);

The months and years can be negative for subtractions. Note that there
The argument of these APIs can be negative for subtractions. Note that there
is some "strange" behaviour when adding and subtracting months at the
ends of months. Generally when the resulting month is shorter than the
starting month then the number of overlap days is added. For example
Expand Down
19 changes: 18 additions & 1 deletion t/07arith.t
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use Test::More tests => 43;
use Test::More tests => 52;

BEGIN { use_ok('Time::Piece'); use_ok('Time::Seconds'); }

Expand Down Expand Up @@ -81,3 +81,20 @@ is($s2->seconds, 0, 'Subtract one Time::Seconds object from another');

eval { $s2 = $s2 + $t; };
like($@, qr/Can't use non Seconds object in operator overload/);

# Tests for add_days
$t = Time::Piece->strptime("01 01 2024","%d %m %Y");
my $t10 = $t->add_days(59);
is($t10->year, 2024);
is($t10->mon, 2);
is($t10->mday, 29);

my $t11 = $t->add_days(-366);
is($t11->year, 2022);
is($t11->mon, 12);
is($t11->mday, 31);

my $t12 = $t->add_days(366);
is($t12->year, 2025);
is($t12->mon, 1);
is($t12->mday, 1);