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
parsedate($date)); my $newdate = strftime("%m/%d/%Y", localtime($newtime));
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.
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.
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
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');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With