Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In perl how can i subtract 10 days from a date which is passed through a text file and output in dd-Month-YYYY(01-jan-1990)

Tags:

datetime

perl

In perl is there a way to subtract 10 days from a date which will be passed from a text file and the output should be in 01-jan-1999 format .

i am using the below code for reading the file and getting the date after that i am strucked with subtracting the date.

date.txt

25-jan-2013

#!/usr/bin/perl
use warnings;
use strict;
use DateTime;

my $inp= "date.txt";
my $todate;
my $fromdate;

open(date,"$inp");
while(<date>)
{
$todate = $_ ;
print "$todate \n";
}

$fromdate = $todate - 10 days ;
like image 771
Ramesh Avatar asked Dec 12 '22 18:12

Ramesh


2 Answers

Here's an answer that uses DateTime.

#!/usr/bin/perl

use strict;
use warnings;
use 5.010;

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

my $parser = DateTime::Format::Strptime->new(
  pattern => '%d-%B-%Y'
);

my $input = '25-jan-2013';

my $todate = $parser->parse_datetime($input);

my $fromdate = $todate->clone;
$fromdate->subtract(days => 10);
say 'From: ', $fromdate->strftime('%d-%B-%Y');
say 'To: ', $todate->strftime('%d-%B-%Y');
like image 100
Dave Cross Avatar answered Jan 05 '23 00:01

Dave Cross


In the old days, you would use Time::Local to convert your time into the number of seconds since the Epoc, subtract the number of seconds in ten days (10 * 24 * 60 * 60), and then convert it back into a time using localtime. It was fun, it was educational, and mostly, it was overly complex and prone to error.

When I'm able to use Perl 5.10 or above, I prefer to use Time::Piece because it makes things simple, and most importantly, it's a standard Perl module. Plus, it plays well with Time::Seconds, another standard Perl module:

use warnings;
use strict;
use autodie;
use feature qw(say);

use Time::Piece;
use Time::Seconds;

my $date = "25-jan-2013";

#Create the "date object". The `%d-%b-%Y" is format the date is in
my $my_date = Time::Piece->strptime($date, "%d-%b-%Y");  #

#Now subtract ten days from it
$my_date -= ( 10 * ONE_DAY );  #Constant from Time::Seconds

say $my_date;   #Prints out Tue Jan 15 00:00:00 2013

#Printing it out in dd-mmm-yyyy format you had
say $my_date->mday . "-" . $my_date->monname . "-" . $my_date->year;
like image 45
David W. Avatar answered Jan 04 '23 23:01

David W.