tags:

views:

89

answers:

6

Hi,

In my script I need to iterate through range of dates given the start date and end date. Please provide me guidance to achieve this using perl.

Thank You

A: 

Perl has a rich array of time and date manipulation modules, as seen here:

http://datetime.perl.org/?Modules

And there are some examples of date and time problems there as well.

With Perl, there's always more than one way to do it.

Steve Morman
+3  A: 

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' );

/I3az/

draegtun
A: 

You can try Date::Calc::Iterator

  # This puts all the dates from Dec 1, 2003 to Dec 10, 2003 in @dates1
  # @dates1 will contain ([2003,12,1],[2003,12,2] ... [2003,12,10]) ;
  my $i1 = Date::Calc::Iterator->new(from => [2003,12,1], to => [2003,12,10]) ;
  my @dates1 ;
  push @dates1,$_ while $_ = $i1->next ;
gangabass
Of course, what is the point of using an iterator if you are just going to push the values to an array?
Sinan Ünür
+2  A: 

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";
}
Zaid
+3  A: 
use DateTime::Format::Strptime qw();
my $start = DateTime::Format::Strptime->new(pattern => '%Y/%m/%d')->parse_datetime('2010/08/16');
my $end   = DateTime::Format::Strptime->new(pattern => '%Y/%m/%d')->parse_datetime('2010/11/24');

while ($start < $end) {
    $start->add(days => 1);
    say $start->ymd('/');
}
daxim
+1  A: 

I like to use the fact that strftime will normalize the date for me:

#!/usr/bin/perl

use strict;
use warnings;

use POSIX qw/strftime/;

my $start = "2010/08/16";
my $end   = "2010/09/16";

my @time        = (0, 0, 0);
my ($y, $m, $d) = split "/", $start;
$y -= 1900;
$m--;
my $offset      = 0;

while ((my $date = strftime "%Y/%m/%d", @time, $d + $offset, $m, $y) le $end) { 
    print "$date\n";
} continue {
    $offset++;
}
Chas. Owens