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

Hi all,

just wonder whether there is a function that returns the last working day of the month?

Title edit by tye

  • Comment on Function to return last working day of month?

Replies are listed 'Best First'.
Re: Functions
by BrowserUk (Patriarch) on Sep 18, 2002 at 14:54 UTC

    Take a look at Date::Manip module on CPAN. It can do this and a whole load more.

    For your specific problem, the following code:

    use Date::Manip; print UnixDate( ParseDate( "last business day of september 2002"), '%F +' );

    gives: Monday, September 30, 2002

    BTW: It would be easier for thise coming along after you to find the answers already given to your problem if you would make your titles a little more specific to the question you are asking.

    Suggestion: "A function to find last business day of the month." - maybe too wordy, but you get the idea :^)


    Cor! Like yer ring! ... HALO dammit! ... 'Ave it yer way! Hal-lo, Mister la-de-da. ... Like yer ring!
Re: Function to return last working day of month?
by sschneid (Deacon) on Sep 18, 2002 at 19:57 UTC
    Date::Manip is definitely the easiest and best way to go about it, but if you're looking for something that doesn't require any CPAN modules (or you don't want to go through the trouble of installing them)...
    #!/usr/local/perl -w # Calculate the last business day of the month. use strict; my $last_day = _calc_last_day(); print "Last business day of the month: $last_day\n"; sub _calc_last_day { use Time::Local; use POSIX qw(strftime); my ($_year, $_month) = split(/\./, `date +%y.%m`); chomp($_year, $_month); # Calculate the last day of the month. my $_next_year = ($_month == 12) ? $_year + 1 : $_year; my $_next_month = timelocal(0, 0, 0, 1, $_month % 12, $_next_year) +; my $_last_day = (localtime($_next_month - 86400))[3]; # Make sure it is a business day. my $_day = strftime "%a", localtime($_next_month - 86400); if ($_day eq 'Sat') { $_last_day--; } if ($_day eq 'Sun') { for (1..2) { $_last_day--; } } return "$_month/$_last_day/$_year"; }

    Enjoy.

    scott.