use Date::Calc qw(Today Add_Delta_YMD Days_in_Month); my ($year, $month, undef) = Add_Delta_YMD( Today(), 0, -1, 0 ); printf "start: %04d-%02d-%02d\n", $year, $month, 1; printf " end: %04d-%02d-%02d\n", $year, $month, Days_in_Month($year, $month);
use DateTime; my $today = DateTime->today(); my $last_month = $today->subtract( months => 1 ); my $first = $last_month->clone()->set_day(1); my $last = $first->add( months => 1 )->subtract( days => 1 ); print "first=$first last=$last\n";
You can also use Time::Local, as shown below. It's not the friendliest module, but it comes with perl.
use Time::Local qw( timegm_nocheck ); my ($y, $m, $d) = (localtime)[5,4,3]; $y += 1900; $m += 1; my $ds = 1; my $de = (gmtime(timegm_nocheck(0,0,0, (1-1), ($m+1)-1, $y)))[3]; printf "start: %04d-%02d-%02d\n", $y, $m, $ds; printf " end: %04d-%02d-%02d\n", $y, $m, $de;
Keep in mind the last day of the month is the day before first day of the next month.
my $mtime = time();
if ($rtime < $mtime + 86400 * 30) {
## Do whatever processing
}
Or you want to find all records within an exact date range, in which case you just store the dates in fixed-width, greatest significance first numerical format and test as necessary:
use strict;
use warnings;
my ($sdate, $edate, $rdate);
$sdate = sprintf('%04d%02d%02d', 2006, 11, 4);
$edate = sprintf('%04d%02d%02d', 2006, 12, 4);
while () {
($rdate) = m/(\d+)/;
print if $sdate <= $rdate && $rdate <= $edate;
}
__DATA__
20061203 Record 1
20061204 Record 2
20061206 Record 3
use strict;
use warnings;
my (@mon, $mon, $year);
@mon = (31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
($mon, $year) = (localtime(time))[4,5];
$year += 1900 if $year < 2000;
if ($mon == 0) {
$mon = 12;
$year--;
}
if ($mon == 2) {
if ($year % 4 != 0) {
$mon[1] = 28;
}
elsif ($year % 400 == 0) {
$mon[1] = 29;
}
elsif ($year % 100 == 0) {
$mon[1] = 28;
}
else {
$mon[1] = 29;
}
}
$year = $year % 100;
print sprintf('%02d/%02d/%02d', $mon, 1, $year),
" through ",
sprintf('%02d/%02d/%02d', $mon, $mon[$mon-1], $year);
perlmonks.org content © perlmonks.org and Anonymous Monk, davidrw, ikegami, saintmike, TedPride
prlmnks.org © 2006 edmund von der burg (eccles & toad)
v 0.03