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

Hi Monks!

Is there a way to find out the week number for any given month? I am looking at "Time::Piece
#!/usr/bin/perl use strict; use warnings; use Time::Piece; # Create Time::Piece New Object my $time = Time::Piece->new(); # Given a date, lets say "2016-04-01". my $date1 = "2016-04-01"; my $date2 = "2016-03-25"; print "Week 1 of April"; print "Week 4 of March";
Any ideas? Thank you all!

Replies are listed 'Best First'.
Re: Week number of the month
by toolic (Bishop) on Mar 25, 2016 at 20:02 UTC
    use warnings; use strict; use Time::Piece qw(); for my $date (qw(2016-04-01 2016-03-25)) { my $t = Time::Piece->strptime($date, '%Y-%m-%d'); my $day_of_month = $t->day_of_month(); my $week_of_month = int($day_of_month/7) + 1; print "Week $week_of_month of ", $t->fullmonth(), "\n"; } __END__ Week 1 of April Week 4 of March
Re: Week number of the month
by GotToBTru (Prior) on Mar 25, 2016 at 19:58 UTC

    What defines which month a week is in?

    Date::Calc looks like it might have the tools you need.

    But God demonstrates His own love toward us, in that while we were yet sinners, Christ died for us. Romans 5:8 (NASB)

      It will be the current day the the code runs: With Time::Piece I can say this:
      # Format YYYYMMDD my $todays = $t->ymd(""); print "Today = 20160325";
Re: Week number of the month
by FreeBeerReekingMonk (Deacon) on Mar 25, 2016 at 22:27 UTC
Re: Week number of the month
by dasgar (Priest) on Mar 27, 2016 at 04:00 UTC

    Part of the challenge is how you are defining the week numbering. For example, April 1, 2016 falls on a Friday. So is April, 1, 2016 in week 0? Or is it week 1?

    Depending on your needs, you can check out DateTime's week_of_month method, which is described as:

    The week of the month, from 0..5. The first week of the month is the first week that contains a Thursday. This is based on the ICU definition of week of month, and correlates to the ISO8601 week of year definition. A day in the week before the week with the first Thursday will be week 0.

    Here's an example code that displays shows some details (name of day, name of month, week of month) for 40 dates starting with the current date.

    Of course, if that does not match the way that you want to determine which week number of the month that a particular date is in, then you may need to come up with some custom code to better match your needs.