Friday, January 21, 2011

How do I find the day or week of the year

The "localtime" function returns the day of the year. Without an argument "localtime" uses the current time.

           $day_of_year = (localtime)[7];

   The "POSIX" module can also format a date as the day of the year or week of the year.

           use POSIX qw/strftime/;
           my $day_of_year  = strftime "%j", localtime;
           my $week_of_year = strftime "%W", localtime;

   To get the day of year for any date, use "POSIX"'s "mktime" to get a time in epoch seconds for the argument to "localtime".

           use POSIX qw/mktime strftime/;
           my $week_of_year = strftime "%W",
            localtime( mktime( 0, 0, 0, 18, 11, 87 ) );

   The "Date::Calc" module provides two functions to calculate these.

           use Date::Calc;
           my $day_of_year  = Day_of_Year(  1987, 12, 18 );
           my $week_of_year = Week_of_Year( 1987, 12, 18 );

No comments: