How can dates be defined in a date range?

What is a good Perl module (or a good approach) that returns all valid calendar dates between a start date and an end date?

For example, if I have 1/29/2009 as the start date and 2/3/2009 as the end date, I would like it to return an array 1/30/2009, 1/31/2009, 2/1 / 2009 and 2/2/2009. There should be a good Perl module that already does this and takes into account leap years, months, but I cannot find it.

Thanks for your suggestions!

+4
source share
6 answers

Date :: Manip seems to be the canonical date module in Perl. This one has a weird API, but it works. Here is an example of using the ParseRecur function to accomplish what you want:

#!/usr/bin/perl use warnings; use strict; use Date::Manip; use Data::Dumper; my ($start, $end) = qw(2009-01-29 2009-02-03); # Exclude start date $start = DateCalc($start, "+1 day"); # y:m:w:d:h:m:s my @dates = ParseRecur('0:0:0:1:0:0:0', $start, $start, $end); for my $date (@dates) { print UnixDate($date, "%Y-%m-%d\n"); } 
+2
source

DateTime , I have used it many times, and it can do almost anything you can think of with dates. It handles leap years, leap seconds, invalid dates / times, it can output dates in any format, it can compare, add, subtract, etc.

The only problem is that this may be redundant.

+9
source

Here is an example using DateTime :

 use strict; use warnings; use DateTime; my $d1 = DateTime->new( month => 1, day => 29, year => 2009); my $d2 = DateTime->new( month => 2, day => 3, year => 2009); while ($d1 <= $d2) { print $d1->strftime("%m/%d/%Y"),"\n"; $d1->add(days => 1); } 
+6
source

Here is a hit. This requires Date::Simple and Date::Range :

 #!/usr/bin/env perl use strict; use warnings; use Date::Simple; use Date::Range; my $d1 = Date::Simple->new('2009-03-02'); my $d2 = Date::Simple->new('2009-03-07'); my $range = Date::Range->new( $d1, $d2 ); for my $date ($range->dates) { print $date->format("%m/%d/%Y"), "\n" # Fixed format } 
+4
source
+3
source

Due to the neat power of POSIX :: mktime, you can do the following:

 use POSIX qw<mktime strftime>; my ( $month, $day, $year ) = ( 8, 16, 2008 ); my $end_date = mktime( 0, 0, 0, 1, 2 - 1, 2009 - 1900 ); while ( 1 ) { my $date = mktime( 0, 0, 0, $day++, $month - 1, $year - 1900 ); push @date_range, strftime( '%x', localtime $date ); last if $date >= $end_date; } 

With mktime( 0, 0, 0, 500, 0, 108 ) it makes sense. But then this is mktime( 0, 0, 0, 0, 2, x ) for the last date of February for any year.

0
source

All Articles