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

Hi Monks!
Can I pass a given month to Time::Piece and get its last day?
#!/usr/bin/perl use strict; use warnings; use Time::Piece; use Time::Seconds qw(ONE_DAY ONE_WEEK ONE_MONTH ONE_YEAR); # Create Time::Piece New Object for the dates my $t = Time::Piece->new(); my $year = $t->year; # Pass November, but it can be any month my $month = "11"; my $last_day_month = $t->month_last_day($month); #?? print $last_day_month." days\n"; # 30

Replies are listed 'Best First'.
Re: Given month last day
by toolic (Bishop) on Aug 28, 2015 at 18:29 UTC
    One way:
    use strict; use warnings; use Time::Piece; my $month = 11; my $t = Time::Piece->strptime($month, '%m'); my $last_day_month = $t->month_last_day(); print "$last_day_month\n"; __END__ 30

    To account for leap years, you may need to also specify the year.

Re: Given month last day
by 1nickt (Canon) on Aug 28, 2015 at 19:17 UTC

    my $last_day_month = $t->month_last_day($month); #??
    Won't work since month_last_day doesn't accept arguments; it returns the object attribute value. So you have to have an object created with the month in question in order to get the last day of the month.

    But you can chain the method calls:

    $last_day = Time::Piece->new->month_last_day;

    What do you mean when you say # Create Time::Piece New Object for the dates? It would be helpful to know what you are trying to accomplish overall. The new() method without arguments creates an object for "now", and if you pass other attributes in but not the year, it will assume you mean the current year. So if you loop through the months and create a T::P object for each one, you will get the last day of the month for months in the current year. This is not accurate if you use the list for other years: as toolic said, due to leap years you will need pass the year to the object creator if you want your code to correctly handle years other than the current year.

    #!/usr/bin/perl use strict; use warnings; use feature qw/ say /; use Time::Piece; for my $year (2015, 2016) { say sprintf("$year/%02d: ", $_), Time::Piece->strptime("$year $_", " +%Y %m")->month_last_day) for 1,2; } __END__
    Output:
    $ perl 1140366.pl 2015/01: 31 2015/02: 28 2016/01: 31 2016/02: 29 $
    The way forward always starts with a minimal test.
Re: Given month last day
by poj (Abbot) on Aug 28, 2015 at 19:25 UTC

    A bit obscure

    $t->add_months(11-$t->mon)->month_last_day;

    clearer

    use Date::Calc qw( Days_in_Month ); print Days_in_Month(2016,2);
    poj
Re: Given month last day
by Anonymous Monk on Aug 28, 2015 at 22:12 UTC
Re: Given month last day
by Anonymous Monk on Aug 30, 2015 at 21:44 UTC
    Using any time-calculation package you please: take the month and year, and calculate the first day of that month/year (month/01/year). Add one month. Then, subtract one day.