From c44fa2e6e96b1164dca75da3be35e9bb6cc9328c Mon Sep 17 00:00:00 2001 From: Guillem Jover Date: Tue, 29 Oct 2019 15:20:58 +0000 Subject: [PATCH] TT#69200 Use Time::Piece and Time::Local to add up months These are core modules, which require no additional dependencies. Change-Id: I8dbda5142dcc9d095a2c703ef6cee5364d2ba55a (cherry picked from commit e6ebcc15c5fd99d5787a2ebde276998bf287f021) --- lib/NGCP/BulkProcessor/Utils.pm | 30 ++++++++---------------------- t/Utils.t | 11 ++++++++++- 2 files changed, 18 insertions(+), 23 deletions(-) diff --git a/lib/NGCP/BulkProcessor/Utils.pm b/lib/NGCP/BulkProcessor/Utils.pm index 2c79282..32fa014 100644 --- a/lib/NGCP/BulkProcessor/Utils.pm +++ b/lib/NGCP/BulkProcessor/Utils.pm @@ -26,6 +26,7 @@ use Cwd qw(abs_path); use Time::Piece; use Time::Seconds; +use Time::Local; use Date::Manip qw(Date_Init ParseDate UnixDate); #Date_Init('Language=English','DateFormat=non-US'); Date_Init('DateFormat=US'); @@ -698,31 +699,16 @@ sub max_timestamp { } sub add_months { + my ($month, $year, $ads) = @_; - my ($month, $year, $ads) = @_; + if ($month > 0 and $month <= 12) { + my $time = timelocal(0, 0, 0, 1, $month - 1, $year); + my $t = Time::Piece->new($time)->add_months($ads); - if ($month > 0 and $month <= 12) { - - my $sign = ($ads > 0) ? 1 : -1; - my $rmonths = $month + $sign * (abs($ads) % 12); - my $ryears = $year + int( $ads / 12 ); - - if ($rmonths < 1) { - $rmonths += 12; - $ryears -= 1; - } elsif ($rmonths > 12) { - $rmonths -= 12; - $ryears += 1; + return ($t->mon, $t->year); + } else { + return (undef, undef); } - - return ($rmonths,$ryears); - - } else { - - return (undef,undef); - - } - } sub secs_to_years { diff --git a/t/Utils.t b/t/Utils.t index bfcfa03..61f5773 100644 --- a/t/Utils.t +++ b/t/Utils.t @@ -16,7 +16,7 @@ use strict; use warnings; -use Test::More tests => 18; +use Test::More tests => 25; use Time::Local; require_ok('NGCP::BulkProcessor::Utils'); @@ -32,6 +32,7 @@ NGCP::BulkProcessor::Utils->import(qw( get_year get_year_month get_year_month_day + add_months )); # zerofill() @@ -58,3 +59,11 @@ is(datestamp($time), '2042-11-02'); is(get_year($time), '2042'); is_deeply([ get_year_month($time) ], [ '2042', '11' ]); is_deeply([ get_year_month_day($time) ], [ '2042', '11', '02' ]); + +is_deeply([ add_months(1, 2042, 11) ] , [ 12, 2042 ]); +is_deeply([ add_months(1, 2042, 12) ] , [ 1, 2043 ]); +is_deeply([ add_months(12, 2042, 0) ] , [ 12, 2042 ]); +is_deeply([ add_months(12, 2042, 1) ] , [ 1, 2043 ]); +is_deeply([ add_months(1, 2042, 25) ] , [ 2, 2044 ]); +is_deeply([ add_months(0, 2042, 2) ] , [ undef, undef ]); +is_deeply([ add_months(13, 2042, 2) ] , [ undef, undef ]);