Check For Leap Year in VB.Net

Discussion in 'Visual Basic [VB]' started by pradeep, May 14, 2007.

  1. pradeep

    pradeep Team Leader

    Joined:
    Apr 4, 2005
    Messages:
    1,645
    Likes Received:
    87
    Trophy Points:
    0
    Occupation:
    Programmer
    Location:
    Kolkata, India
    Home Page:
    http://blog.pradeep.net.in
    When dealing with dates in VB.NET, it's a good idea not to perform manual checks or calculations, which may be inaccurate depending on the quality of the code. Instead, it's advisable to rely on the functionality of classes provided by .NET.

    For instance, if you need to determine if a given year is a leap year, you can use VB.NET's IsLeapYear function. Here's an example of how you can use the function:

    Code:
     Private Sub LeapYearCheck()
         Dim bLeapYear AsBoolean
     
         bLeapYear = Date.IsLeapYear(Now.Year)
         MessageBox.Show(bLeapYear)
     
         bLeapYear = Date.IsLeapYear(2004)
         MessageBox.Show(bLeapYear)
     End Sub
     
    In the example, we define a Boolean variable, bLeapYear, to hold the result of whether a given year is a leap year. we then set the value of bLeapYear to the IsLeapYear property of the Date class and pass to it the current year, which we obtain using the Year property of the Now class. We show the value of bLeapYear in a MessageBox. The result is False because 2007 is not a leap year. After that,we follow the same steps for 2004, which is a leap year. In that case, MessageBox shows True.
     
  2. tailhook123

    tailhook123 New Member

    Joined:
    May 23, 2007
    Messages:
    30
    Likes Received:
    0
    Trophy Points:
    0
    bLeapYear = Date.IsLeapYear(Now.Year)

    Nice.. whats the class type for the Date variable you are using?

    Is it just like Dim Date asDate?

    And the reason this code can be tricky if done manually is that common knowledge is that there is a leap year every 4 years. Uncommon knowledge is that there is an extra rule that any year divisible by 100 but not divisible by 400 is not a leap year.

    So 1900 wasn't a leap year while 2000 was.
     
  3. pradeep

    pradeep Team Leader

    Joined:
    Apr 4, 2005
    Messages:
    1,645
    Likes Received:
    87
    Trophy Points:
    0
    Occupation:
    Programmer
    Location:
    Kolkata, India
    Home Page:
    http://blog.pradeep.net.in

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice