Downloads
48663.zip

The LeapYear function, which Listing 1, page 16, shows, can be a handy little snippet when you code date logic, particularly if you have a user-provided start or end date. For most months, it's relatively simple to determine a valid day entry by checking the maximum number of days in a specific month. You could evaluate the number of days with a simple Select Case statement. The value would be either 30 or 31. If a user entered April 31, for instance, the Select Case statement could correct it to April 30.

But there always seems to be an exception to the rule. In this case, it's the coldest of all months (at least where I'm from): February. Determining the number of days in February requires a little more work.

The simplest way I have found to evaluate February is to get the "day number" for March 1. For example, January 1 is day number 1 and February 1 is day number 32. March 1 is day number 60 in a nonleap year and day number 61 in a leap year.

The LeapYear function takes one argument: any year from 0 to 9999. The LeapYear function concatenates that year with March 1, converts the resulting string to a Date type value using VBScript's CDate function, and assigns that date value to a variable named chkdate, as callout A in Listing 1 shows. VBScript's DatePart function then uses the chkdate variable along with the "y" parameter (which indicates a time interval of day of year) to return the day number for March 1 of that given year.

If the user provides in an invalid date, both the CDate and DatePart functions throw an error, which prompts the function to exit. If the user provides a valid date, the day number is evaluated. If the day number is greater than 60, the LeapYear function returns True (i.e., the year is a leap year). Otherwise, the LeapYear function returns False.

Listing 2 demonstrates how you might use the LeapYear function in a script. This script uses a simple input box to get a year from the user. You can also use the LeapYear function within an HTML Application (HTA). You can download a sample HTA, LeapYearFunction-Demo.hta, from the Windows Scripting Solutions Web site. Go to http://www.windowsitpro.com/windowsscripting, enter 48663 in the InstantDoc ID text box, then click the 48663.zip hotlink.

SNIPPET SNAPSHOT
The LeapYear Function

Purpose: Determines whether the specified year is a leap year
Language: VBScript