user2684009
user2684009

Reputation: 167

Accounting for Leap Years VB.net

I have the following piece of code which starts the looking at year to date from Feb 1 instead of Jan 1. I have made the change, however It doesn't account for leap years. How can I modify this code to ensure that it accounts for the leap years. I am relatively new in VB. IS there a built in function that does?

Dim dt As Date
    Dim Y2Dday As Integer
    Dim Y2Dyear As Integer
    Dim strDepartment1 As String

    dt = dtpDate.Value
    'Y2Dday = -dt.DayOfYear + 32
    Y2Dday = -dt.DayOfYear + 366
    'If dt.DayOfYear > 31 Then
    If dt.DayOfYear > 365 Then
        Y2Dyear = 0
    Else
        Y2Dyear = -1
    End If
    strDepartment1 = strDepartment.Replace("departmentid", "o.departmentid")

    Dim collection As ItemCollection
    Dim qry As QueryItem

    collection = ItemCollection.GetInstance()
    qry = collection.GetQueryItem(intItem)
    If (Not qry Is Nothing) Then
        qry.SetQueryParameter(QueryItem.QueryParameter.DateFormat, intDateFormat.ToString())

        qry.SetQueryDate(1, dt.ToString)
        'Date used by Item(s) looking at Month to Date
        qry.SetQueryDate(2, dt.AddDays(-dt.Day + 1).ToString)

        'Date used by Item(s) looking at Year to Date
        qry.SetQueryDate(3, dt.AddDays(Y2Dday).AddYears(Y2Dyear).ToString)

        'Date used by Item(s) looking at Yesterday
        qry.SetQueryDate(4, dt.AddDays(-1).ToString)

Upvotes: 1

Views: 1214

Answers (1)

the DateTime Type includes a IsLeapYear(year as Integer) function. It is a Shared/Static function, so you invoke it using DateTime with a year value:

IsLeap = DateTime.IsLeapYear(myYearValue)
'  or
IsLeap = DateTime.IsLeapYear(myDt.Year)

or as an If:

If DateTime.IsLeapYear(myDate.Year) Then ...

It might seem confusing not being able to do myDateVar.IsLeapYear, but it allows you to test a year value without having to create a DateTime variable first.

Upvotes: 8

Related Questions