Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?
 
PerlMonks  

Re: How to get last month date period

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


in reply to How to get last month date period

You can use strftime from POSIX to format the date, and timelocal from Time::Local to do basic time manipulation. Both are core modules, i.e. they come with Perl.

So, what I propose is the following steps:

  • with localtime, get the list of date and time values for today/now into an array
  • set the day of the month to the first, so you have the date of the first of this month. You may set the time to (around) noon to avoid problems with the switch of Daylight Saving Time, where a day is not exactly 24 hours, depending on what time of day it is now.
  • convert to seconds since epoch with timelocal
  • subtract 24*60*60 seconds to get a time in the last day of the past month as an integer value
  • with localtime, convert to the list of date and time values
  • use strftime to get the last day, properly formatted
  • in the array, set the day to the first.
  • use strftime to get the first day, properly formatted

Code:

use POSIX; use Time::Local; print daterange(); sub daterange { my @dt = localtime; $dt[3] = 1; $dt[2] = 12; my $time = timelocal @dt; $time -= 24*60*60; @dt = localtime $time; my $ret = strftime("%d %b %Y", @dt); $dt[3] = 1; return strftime("%d %b %Y", @dt) . " - $ret"; }


Comment on Re: How to get last month date period
Select or Download Code

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others examining the Monastery: (2)
As of 2014-08-31 01:51 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The best computer themed movie is:











    Results (294 votes), past polls