Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to iterate through range of Dates?

Tags:

windows

perl

In my script, I need to iterate through a range of dates given the start date and end date. How can I do this in Perl?

like image 705
nimo Avatar asked Dec 13 '22 20:12

nimo


2 Answers

Use DateTime module. Here is a simple example which lists the ten previous days:

use 5.012;
use warnings;
use DateTime;

my $end = DateTime->now;
my $day = $end->clone->subtract( days => 10 );  # ten days ago

while ($day < $end) {
    say $day;
    $day->add( days => 1 );   # move along to next day
}

 

Update (after seeing your comment/update):

To parse in a date string then look at the DateTime::Format on modules CPAN.

Here is an example using DateTime::Format::DateParse which does parse YYYY/MM/DD:

use DateTime::Format::DateParse;
my $d = DateTime::Format::DateParse->parse_datetime( '2010/06/23' );
like image 187
draegtun Avatar answered Dec 28 '22 14:12

draegtun


One easy approach is to use the Date::Simple module, which makes use of operator-overloading:

use strict;
use warnings;
use Date::Simple;

my $date    = Date::Simple->new ( '2010-01-01' );  # Stores Date::Simple object
my $endDate = Date::Simple->today;                 # Today's date

while ( ++$date < $endDate ) {

    print ( $date - $endDate ) , "day",
          ( ( $date-$endDate) == 1 ? '' : 's' ), " ago\n";
}
like image 41
Zaid Avatar answered Dec 28 '22 15:12

Zaid