1. Perl
  2. Date/Time

Get the last day of the month

This is an example function to get the last day of the month. The timelocal function of the Time::Local module is used to check the existing date.

use strict;
use warnings;

print "(1) Get the last day of the month.\n";
my $end_of_month_200802 = end_of_month (2008, 2);
print "The last day of February 2008 is $end_of_month_200802.\n";

# A function that finds the last day of the month.
sub end_of_month {
  my ($year, $month) = @_;
  return if !$year ||!$month;

  # Time::Local::timelocal function takes an elapsed year from 1900 as an argument
  # Since it is taken to , subtract 1900.
  $year-= 1900;

  # Time::Local::timelocal function starts from 0 like 0 in January and 1 in February
  # Takes the month that starts as an argument, so subtract 1.
  $month-;

  # These four candidates for the end of the month
  my @days = (31, 30, 29, 28);
    
  # Used for checking the existence of dates.
  require Time::Local;
  
  for my $day (@days) {
    eval {
      # If you specify a non-existent day, an exception will be thrown.
      Time::Local::timelocal (0, 0, 0, $day, $month, $year);
    };
    # Date that exists if no exception occurs.
    return $day unless $@;
  }
  return;
}

(Reference) eval

Code explanation

Candidate date for the last day of the month

The last day of the month is 28th, 29th, 30th, or 31st. If the date is checked in order from the 31st and exists, it is the last day of the month.

my @days = (31, 30, 29, 28);

Check existing dates

Check the date with the timelocal function of the Time::Local module, as explained in "Determining if a date exists."

We will check from the 31st to the 28th. If you specify a date that does not exist, an exception will be thrown, so if no exception is raised, it is the last day of the month.

require Time::Local;
  
for my $day (@days) {
  eval {
    # If you specify a non-existent day, an exception will be thrown.
    Time::Local::timelocal (0, 0, 0, $day, $month, $year);
  };
  # Date that exists if no exception occurs.
  return $day unless $@;
}

Related Informatrion