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"; }
|
---|
In Section
Seekers of Perl Wisdom