Search code examples
vb.netdateleap-year

Can you force values into the Date type?


I've come across a bug where the expedient solution would be to somehow force certain values into the Date type.

It would include being able to do the following Dim myDate As Date = New Date(1900, 2, 29).

The 29th of February is a leap day but 1900 is not a leap year, therefore, this is not a valid date and it doesn't allow it to even be created. Is there a way you can create it with these values?


Solution

  • You can't force an invalid date into a System.DateTime. Have a look here: https://learn.microsoft.com/en-us/dotnet/api/system.datetime?view=netframework-4.8

    Why don't you use the Date.IsLeapYear(1900) to check which date value you should set?

    Here are 2 examples:

        Dim myDate As Date
        Dim myYear As Integer = 1900
        If Date.IsLeapYear(myYear) Then
            myDate = New Date(1900, 2, 28)
        Else
            myDate = New Date(1900, 2, 29)
        End If
    
        Dim myDate2 As Date
        Dim myYear2 As Integer = 1900
        If Date.IsLeapYear(myYear2) Then
            myDate2 = New Date(1900, 3, 1)
        Else
            myDate2 = New Date(1900, 2, 29)
        End If