Bootstrap FreeKB - Perl (Scripting) - Add or subtract time using Time::Piece and Time::Seconds (timepiece)
Perl (Scripting) - Add or subtract time using Time::Piece and Time::Seconds (timepiece)

Updated:   |  Perl (Scripting) articles

If you are not familiar with Time::Piece (timepiece), check out my article Date and Time using Time::Piece (timepiece).

Here is a basic example of how to use the Time::Piece module.

#!/usr/bin/perl
use strict;
use warnings;
use Time::Piece;
my $timepiece = Time::Piece->new();
print "$timepiece \n";

 

This should return something like this.

Wed Jan 26 05:48:39 2022

 

Let's say you want to adjust the date, such as going forward or backwards one month.The Time::Seconds module can be used to add or substract minutes, hours, days, weeks, months or years from a date time. 

  • ONE_HOUR
  • ONE_MINUTE
  • ONE_DAY
  • ONE_WEEK
  • ONE_MONTH
  • ONE_FINANCIAL_MONTH
  • ONE_YEAR
  • LEAP_YEAR
  • NON_LEAP_YEAR
#!/usr/bin/perl
use strict;
use warnings;
use Time::Piece;
use Time::Seconds;

my $timepiece = Time::Piece->new;
my $one_month_forward   = ($timepiece + ONE_MONTH);
my $two_months_forward  = ($timepiece + ONE_MONTH * 2);
my $one_month_backward  = ($timepiece - ONE_MONTH);
my $two_months_backward = ($timepiece - ONE_MONTH * 2);
my $one_day_forward     = ($timepiece + ONE_DAY);
my $one_days_backward   = ($timepiece - ONE_DAY);
my $two_days_backward   = ($timepiece - ONE_DAY * 2);

 

Optionally, strftime can be used to format the output.

#!/usr/bin/perl
use strict;
use warnings;
use Time::Piece;
use Time::Seconds;

my $timepiece = Time::Piece->new;
my $one_month_forward  = ($timepiece + ONE_MONTH)->strftime("%m/%d/%Y");

 

Which should produce a result in this format in this example.

11/23/2021

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter a431b0 in the box below so that we can be sure you are a human.