Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight

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


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"; }

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://826736]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (12)
As of 2017-01-18 14:39 GMT
Find Nodes?
    Voting Booth?
    Do you watch meteor showers?

    Results (161 votes). Check out past polls.