Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl script - add days to Date to get new date

Tags:

date

perl

I am working on a perl script to add days to a date and display the newdate:

use Time::ParseDate;
use Time::CTime;

my $date = "02/01/2003";
my $numdays = 30;

my $time = parsedate($date);

# add $numdays worth of seconds
my $newtime = $time + ($numdays * 24 * 60 * 60);

my $newdate = strftime("%m/%d/%Y",localtime($newtime));

print "$newdate\n";

    The output will be:

    03/03/2003

Now how do I set the input for the date field to be yyyymmdd Ex: my $date = "20030102"

Also the output will need to be : 20030303

Thanks

like image 769
Gallop Avatar asked Oct 29 '12 13:10

Gallop


People also ask

How do I add days to a date in Perl?

parsedate($date)); my $newdate = strftime("%m/%d/%Y", localtime($newtime));

What is Strftime in Perl?

You can use the POSIX function strftime() in Perl to format the date and time with the help of the following table. Please note that the specifiers marked with an asterisk (*) are locale-dependent. Specifier. Replaced by.

How do I add a timestamp to a Perl script?

Creating a Timestamp Timestamp can be created by creating a DateTime object and then calling the now constructor. my $datetime = DateTime->now; print "$datetime\n" ; A DateTime object can also be created by providing all the details part wise like date, hour, minute, second, etc.


2 Answers

You can use DateTime + DateTime::Format::Strptime:

#!/usr/bin/perl
use strict;

use DateTime;
use DateTime::Format::Strptime;

my $strp = DateTime::Format::Strptime->new(
    pattern => '%m/%d/%Y'
);

# convert date to 
my $date = '02/01/2003';
my $dt   = $strp->parse_datetime($date);
printf "%s -> %s\n", $date, $dt->add(days => 30)->strftime("%d/%m/%Y");

OUTPUT

02/01/2003 -> 03/03/2003
like image 83
Pavel Vlasov Avatar answered Sep 21 '22 13:09

Pavel Vlasov


You use Time::Piece + Time::Seconds (in core since Perl 5.10),

use Time::Piece ();
use Time::Seconds;
my $date = '20030102';
my $numdays = 60; # 30 doesn't get us to march

my $dt = Time::Piece->strptime( $date, '%Y%m%d');
$dt += ONE_DAY * $numdays;
print $dt->strftime('%Y%m%d');
like image 36
MkV Avatar answered Sep 24 '22 13:09

MkV