Sunday, March 2, 2008

Leap Years

This year (2008) is a leap year, and this past week contained February 29. It seems only fitting that we talk about calculating leap years and what we can do with that information.


A leap year is always divisible by four, but not by one hundred unless it is also divisible by four hundred.


ASP

  1. function isLeapYear(someYear)
  2.     if someYear Mod 4 = 0 and (someYear Mod 100 <> 0 or (someYear Mod 100 = 0 and someYear Mod 400 = 0)) then
  3.         isLeapYear = True
  4.     else
  5.         isLeapYear = False
  6.     end if
  7. end function

PHP

  1. function isLeapYear($someYear)
  2. {
  3.     return date("L", strtotime($someYear . "-01-01"));
  4. }

Now let's write a function to build on this which returns the number of days in a given month.


ASP

  1. function MonthDays(someMonth, someYear)
  2.     select case someMonth
  3.     case 1, 3, 5, 7, 8, 10, 12
  4.         MonthDays = 31
  5.     case 4, 6, 9, 11
  6.         MonthDays = 30
  7.     case 2
  8.         if isLeapYear(someYear) then
  9.             MonthDays = 29
  10.         else
  11.             MonthDays = 28
  12.         end if
  13.     end select
  14. end function

PHP

  1. function MonthDays($someMonth, $someYear)
  2. {
  3.     return date("t", strtotime($someYear . "-" . $someMonth . "-01"));
  4. }

UPDATE: Thanks to Jim Mayes for showing me more elegant PHP solutions.

No comments: