Just another Perl shrine PerlMonks

### Re: How to get last month date period

by almut (Canon)
 on Mar 04, 2010 at 16:20 UTC ( #826733=note: print w/replies, xml ) Need Help??

in reply to How to get last month date period

As this is mostly static info (except for leap years), you might just want to use a simple lookup table.

```my %period = (
Jan => ['01 Dec','31 Dec'],
Feb => ['01 Jan','31 Jan'],
Mar => ['01 Feb','28 Feb'],
#...
Dec => ['01 Nov','30 Nov'],
);

my \$curr_month = "Mar";
my \$curr_year  = 2010;

my \$p = \$period{\$curr_month};
print "\$p->[0] \$curr_year - \$p->[1] \$curr_year\n";   # 01 Feb 2010 - 2
+8 Feb 2010

To figure out when the "28 Feb" isn't correct, you could use one of the many date modules on CPAN (this is left as an exercise for... :).  Or simply hardcode a list of those years up until the time you'll retire ;)

Update: the following should also work for up to 2099

```...
my \$p = \$period{\$curr_month};
if (\$curr_month eq "Mar") {
\$p->[1] = '29 Feb' unless \$curr_year % 4;
}
...

Replies are listed 'Best First'.
Re^2: How to get last month date period
by bart (Canon) on Mar 04, 2010 at 16:51 UTC
This will break in January.

As for leap years, the rule is:

• Assume 28 days, except:
• if the current year divisible by 4: 29 days, except
• if the current year is divisible by 100: 28 days except:
• if the current year is divisible by 400: 29 days
This will break in January.

You're right.  To fix, just add:

```\$curr_year-- if \$curr_month eq "Jan";
Re^2: How to get last month date period
by roborat (Novice) on Mar 04, 2010 at 16:28 UTC
Hi Almut, thanks a lot for the help! I'll find out how to check it 28 Feb isn't correct. :)

Hope to find the solution to this soon. :)
Thanks you very much!

Create A New User
Node Status?
node history
Node Type: note [id://826733]
help
Chatterbox?
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others imbibing at the Monastery: (6)
As of 2018-04-24 15:09 GMT
Sections?
Information?
Find Nodes?
Leftovers?
Voting Booth?
My travels bear the most uncanny semblance to ...

Results (86 votes). Check out past polls.

Notices?