in reply to Getting previous dates from the current date

Date::Calc will do what you want, but if you need more flexibility, try Date::Manip
  • Comment on Re: Getting previous dates from the current date

Replies are listed 'Best First'.
Re^2: Getting previous dates from the current date
by cazz (Pilgrim) on Mar 29, 2005 at 16:16 UTC
    Actually, don't even bother with any of the modules. simple math is all you need.
    my $NUM_DAYS = 7; my $time = time(); print scalar localtime ($time - (60*60*24*$NUM_DAYS));
    Then just strftime to whatever format you need.
      simple math is all you need.

      Except that the mathematics of date-handling is rarely simple. In this case you've made the error of assuming there are 24 hours in the day.

      In the UK, for example, the clocks have just moved forwards by an hour for British Summer Time: Sunday only had 23 hours in it.

      Most of the time your code will work just fine. But if it happens to be run in the first hour of a day then it will yield the wrong output, skipping a day.

      For example, if I ran it at 00:17 early tomorrow (Wednesday) morning with $NUM_DAYS set to 2 then it would correctly output:

      Mon Mar 28 00:17:00 2005

      But setting $NUM_DAYS to 3 would yield:

      Sat Mar 26 23:17:00 2005

      The original poster just wanted dates; if you truncate the time portions off the above then you've ended up skipping a day, jumping straight from Monday to Saturday!

      Now it would be possible to fix this, but it isn't worth trying when so many hours of hard thinking have already been put into getting these sorts of things write by the creators of the DateTime module and friends.

      Do not try to do arithmetic with dates. You will get it wrong.

      Smylers

      Rather than time(), I'd suggest using...

      use Time::Local; my $time = timelocal(0, 0, 12, (localtime)[3, 4, 5]);

      This'll make midday your starting point for calculations, which helps sidestep the whole daylight savings issue Smylers pointed out.

      As an added bonus, Time::Local is also part of the core distribution, so you don't need to install anything via CPAN (which is good, as some of those other more fancy Date:: modules are mighty bloaty!).

          --k.