Calculate date ranges in Perl

I needed to calculate a date range in Perl, to work out today's date and the 14 previous days. There are plenty of ways to do it, but I didn't really want to install a module like Date::Range to do something this simple.

So, my solution was:

my $ctime = time;
 
my $days = 14;
my @dates;
 
while (@dates < $days) {
    push @dates, scalar localtime $ctime;
    $ctime -= (60 * 60 * 24);
}
 
print "dates are:\n";
print "$_\n" for @dates;

That worked nicely.

To format the dates the way I wanted (as SQL-ready dates) I then changed it to:

my $ctime = time;
 
my $days = 14;
my @dates;
 
while (@dates < $days) {
    my ($day, $month, $year) = (localtime($ctime))[3..5];
    $year += 1900;
    $month++;
 
    push @dates, sprintf('%04d-%02d-%02d', $year, $month, $day);
    $ctime -= (60 * 60 * 24);
}
 
 
print "dates are:\n";
print "$_\n" for @dates;

That worked a treat.

In case it's not obvious already, the output of that script will look like:

[davidp@ruthenium:~]$ perl daterangetest.pl 
dates are:
2007-09-06
2007-09-05
2007-09-04
2007-09-03
2007-09-02
2007-09-01
2007-08-31
2007-08-30
2007-08-29
2007-08-28
2007-08-27
2007-08-26
2007-08-25
2007-08-24
 
perl/daterange.txt · Last modified: 2010/02/26 10:45 (external edit)
 
Recent changes RSS feed Donate Powered by PHP Valid XHTML 1.0 Valid CSS Driven by DokuWiki