Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

How can I have a perl script count the days since Feb 09 this year? All I want to do is count the days since then. Any hints?

Replies are listed 'Best First'.
Re: counting days
by borisz (Canon) on Apr 07, 2004 at 10:35 UTC
    #!/usr/bin/perl use Date::Calc qw/Delta_Days Today/; print Delta_Days(2004,2,9, Today() );
    Boris
Re: counting days
by broquaint (Abbot) on Apr 07, 2004 at 10:39 UTC
    The simple approach would be to use Date::Simple e.g
    use Date::Simple qw/ date today /; my $past = '2004-02-09'; printf "%d days have passed since %s\n", today() - date($past), $past; __output__ 58 days have passed since 2004-02-09
    HTH

    _________
    broquaint

Re: counting days
by bart (Canon) on Apr 07, 2004 at 10:36 UTC
    Convert the date of Feb 09 2004 to an epoch time. Read the current time. Subtract the two, and divide by (24*60*60). That's the number of days since then, you'll want to apply int() to it to get the whole number of days. Some code:
    use Time::Local; # module comes with Perl, so don't worry my $start = timelocal(0, 0, 0, 9, 1, 2004); printf "Days since Feb 9: %d days\n", int((time - $start)/(24*60*60));
    which, for me and now, prints:
    Days since Feb 9: 58 days
    

    It does have a problem with summertime (AKA dayligh saving time), though... One day didn't have 24 hours, but just 23. It'll count multiples of 24 hours alright, but it won't switch over at midnight any more.

    Update If you really want calendar days, not just multiples of 24 hours, here's a quick fix. Use gmtime/timegm() instead of localtime/timelocal() for the calculations, as that doesn't care about daylight saving time. So fake it, act as if the current local time is actually gmtime, and take the calculations from there. Updated code that does that:

    use Time::Local; # module comes with Perl, so don't worry my $start = timegm(0, 0, 0, 9, 1, 2004); printf "Days since Feb 9: %d days\n", int((timegm(localtime) - $start) +/(24*60*60));

    Thanks to the fact that timegm() takes its parameters just the way localtime() returns them in list context, while ignoring exces parameters, the interface between the two is very simple.