Checking days in a month

Top Japanese page




Overview

Check the day of the specified month. If checkdate method of Date::Calc is used, it's easier. But in here, introduce a code.

Flow

  1. Get year, month and day information
  2. Set days of each year
  3. Get the day of the specified month
  4. Check if it's leap year and fix the day of Febrary
  5. If the given date is within that month, return 1, else return 0

A sample code

 sub monthdaycheck {
   my ($year,$month,$day) = @_;
   my @monthdays = (31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
   my $md = $monthdays[$month-1];
   ++$md if ($month == 2 and $year % 4 == 0 and ($year % 100 != 0 or $year % 400 == 0));
   return ($day <= $md and $day >= 1 and $year >= 1);
 }

Description of the code

 sub monthdaycheck {
   my ($year,$month,$day) = @_;

Get year, month and day information.

   my @monthdays = (31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);

Put day information into an array.

   my $md = $monthdays[$month-1];

Get the maximum day of the given month.

   ++$md if ($month == 2 and $year % 4 == 0 and ($year % 100 != 0 or $year % 400 == 0));

If it's a leap year, add 1.

   return ($day <= $md and $day >= 1 and $year >= 1);
 }

If the given month is within that maximum day number, return 1, otherwise, return 0.