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

If I wanted to find out what day of the year it is, how would I do that in Perl? I know I could easily just do a `date +%j` or something, but I'm curious how it could be done with the language itself in a manner that's OS-independent.

Also, if I wanted to find out how many days there are between two dates, how might I go about doing it? For example, if I wanted to calculate how many days there are between now and June 17th of 2003, how could it be done?

Thanks for any suggestions :)

Replies are listed 'Best First'.
Re: Date Calculation
by Enlil (Parson) on Nov 08, 2002 at 22:20 UTC
    For the day of the year today falls on you could just use:
    $day_of_the_year = (localtime)[7];
    For the days between dates (and all your date/time needs), try searching CPAN for date, but for your current question Date::Calc would be a good place to start.

    -enlil

Re: Date Calculation
by gjb (Vicar) on Nov 08, 2002 at 22:14 UTC

    You could have a look at Date::Calc which allows for a lot of date related transformations.

    Hope this helps, -gjb-

Re: Date Calculation
by tadman (Prior) on Nov 08, 2002 at 22:59 UTC
    Of course, everyone is quick on the draw with Date::Calc, but I think you've already solved the problem yourself.
    use POSIX 'strftime'; my $day = strftime("%j", localtime(time()));
    You'll find that the date command and strftime have, not surprisingly, a lot in common.

    The alternative is to access the appropriate entry in the localtime array, as suggested by Enlil.
Re: Date Calculation
by VSarkiss (Monsignor) on Nov 08, 2002 at 22:24 UTC
Re: Date Calculation
by Segfault (Scribe) on Nov 09, 2002 at 02:49 UTC
    Thanks a bunch, everyone - Date::Calc did the trick perfectly. :)
Re: Date Calculation
by jjdraco (Scribe) on Nov 08, 2002 at 22:23 UTC
    theres very question was the problem for week 1 of QOTW you should go check out the archives, or check out CPAN it has some good modules for doing this. theres a lot of little things you have to be careful of when dealing with dates and its just eaiser to use one of CPANs modules than to try and roll you're own

    jjdraco
    learning Perl one statement at a time.