
davorg
Thaumaturge
/ Moderator
Dec 1, 2003, 3:54 AM
Post #3 of 5
(258 views)
|
(By the way, I've moved this to be a separate thread. It's never a good idea to ask a new question in an existing thread.) The easiest way to deal with dates in Perl is to use the same representation that Perl does. That is to convert dates and times to the number of seconds since some arbitrary point. For most systems that point is defined as 1st Jan, 1970 (this system can therefore be flaky for dates before that). You can always get the current in that format using the "time" function. This is currently a number that is just over 1e9. Now all you need to do is to convert a date in YYYYMMDD to one of these "epoch seconds" values. I suggest you write a function for this and use the standard Time::Local module.
use Time::Local; sub date2epoch { my $date = shift; my ($y, $m, $d) = $date =~ /(\d\d\d\d)(\d\d)(\d\d)/; # check the match worked unless ($y && $m && $d) { die "invalid date $date\n"; } # assume midnight # see perldoc -f Time::Local for parameter definitions my $epoch = timelocal(0, 0, 0, $d, $m - 1, $y - 1900); return $epoch; } You can then compare dates to the current time to see if they appeared in the previous week (i.e. 7 * 24 * 60 * 60 seconds).
my $date = '20031128'; # or whatever use const ONE_WEEK => (7 * 24 * 60 * 60); if ($now - date2epoch($date) < ONE_WEEK) { print "$date is in the last week\n"; } -- Dave Cross, Perl Hacker, Trainer and Writer http://www.dave.org.uk/ Get more help at Perl Monks
|