

Title  Determine whether a year is a leap year with Visual Basic 2005 
Description  This example shows how to determine whether a year is a leap year with Visual Basic 2005. 
Keywords  leap year, year, dates 
Categories  Miscellany, Strings 


Thanks to WJK.
This example contains four functions that determine whether a year is a leap year. When the program starts, it uses each to see which years between 1880 and 2020 are leap years and adds them to four list boxes, one for each function. If you make the form tall enough, you can see that they all agree.


Public Function IsLeapYear0(ByVal y As Integer) As Boolean
On Error Resume Next
IsLeapYear0 = False
'If the year is evenly divisible by 4 and not by 100,
' then this
'is a leap year.
If y Mod 4 = 0 And y Mod 100 <> 0 Then
IsLeapYear0 = True
'If the year is evenly divisible by 4 and 100, then
' check to
'see if the quotient of year divided by 100 is also
' evenly
'divisible by 4. If it is, then this is a leap year.
ElseIf y Mod 4 = 0 And y Mod 100 = 0 Then
If (y \ 100) Mod 4 = 0 Then IsLeapYear0 = True
End If
End Function
Private Function IsLeapYear1(ByVal y As Integer) As Boolean
If y Mod 4 <> 0 Then Return False
If y Mod 400 = 0 Then Return True
If y Mod 100 = 0 Then Return False
Return True
End Function
Private Function IsLeapYear2(ByVal y As Integer) As Boolean
Return (y Mod 4 = 0) AndAlso _
((y Mod 100 <> 0) OrElse (y Mod 400 = 0))
End Function
Private Function IsLeapYear3(ByVal y As Integer) As Boolean
Return IsDate("2/29/" & y)
End Function


After I posted this example, Alexander Klimoff (rusproject AT mail.ru) pointed out that the DateTime class has an IsLeapYear function! Here's the code the new example uses for this technique:
If DateTime.IsLeapYear(i) Then lstDateTime.Items.Add(i)





