Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid
 
PerlMonks  

Re: How do i get "the last day of last month"?

by grantm (Parson)
on Apr 28, 2003 at 03:37 UTC ( [id://253586]=note: print w/replies, xml ) Need Help??


in reply to How do i get "the last day of last month"?

Or, if you only have core modules at your disposal, then you could work out the first of next month and subtract a day:

use strict; use Time::Local; use constant ONE_DAY => 24 * 60 * 60; my ($sec,$min,$hour,$mday,$mon,$year) = localtime(); $mday = 1; $mon = ($mon + 1) % 12; $year += 1 if($mon == 0); my $time = timelocal($sec,$min,$hour,$mday,$mon,$year) - ONE_DAY; print scalar localtime($time);

Update: Sorry, I completely misread the question and gave you the last day of this month. The last day of last month is a little easier:

use Time::Local; use constant ONE_DAY => 24 * 60 * 60; my ($sec,$min,$hour,$mday,$mon,$year) = gmtime(); $mday = 1; my $time = timegm($sec,$min,$hour,$mday,$mon,$year) - ONE_DAY; print "Date: " . localtime($time) . "\n"; $mday = (localtime($time))[3]; print "Day of month: $mday\n";

Update 2: As MarkM notes below, daylight savings changes could trip these snippets up. I originally coded them to set $sec, $min and $hour all to zero and then subtract say 4 hours - which I think should be pretty safe. I changed it before posting because I thought it was a bit obfuscated - but clear code that's wrong is no less wrong :-)

Replies are listed 'Best First'.
Re: Re: How do i get "the last day of last month"?
by MarkM (Curate) on Apr 28, 2003 at 03:46 UTC

    I am not particularly fond of this solution as it does not take daylight savings time into account. Sure, most time zones don't adjust their time on the first or last of a month, however, this is not a rule in stone.

    Then again, though, Date::Manip, and a few of the other modules are quite broken when it comes to time zones, so I shouldn't be too critical of a core-perl solution. :-)

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://253586]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (4)
As of 2024-03-29 01:35 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found