I was wondering if there is an in-built Perl function that adjusts the date if you take a month from it. E.g. if date is the 31st, it will adjust to be the end of the previous month if it doesn’t have 31 days.
I would just change it to 30th easily if it weren’t for the months with 31 days next to each other (Dec/Jan, Jul/Aug) and February.
I just want to store the date a certain amount of time away from the current date, e.g.
my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time);
$current_date = join("-", (1900+$year), ($mon+1), $mday);
$one_month_ago = join("-", (1900+$year), ($mon), $mday);
$one_year_ago = join("-", (1899+$year), ($mon+1), $mday);
I can deal with the February instance as it only applies to years, but if this was taken on the 31st December 2012 then taking away a month would mean 31st Nov 2012, which of course didn’t exist. I thought I would ask if there was a function before complicating things for myself… thanks 🙂
Others have suggested
DateTime, but it’s quite large, non-core, and can be slow.A much simpler solution is to use the builtin
localtimeandPOSIX::mktimefunctions:The
mktime()function specifically handles denormalised values; it will cope with the fact that Janurary minus 2 months is November of the previous year, etc.. It will keep the same second/minute/hour of the day, and the same day of the month.