您可以将值强制转换为 Date 类型吗?

Can you force values into the Date type?

我遇到了一个错误,其中权宜之计的解决方案是以某种方式强制某些值到Date类型。

它将包括能够执行以下操作 Dim myDate As Date = New Date(1900, 2, 29)

2 月 29 日是闰日,但 1900 不是闰年,因此,这不是一个有效的日期,甚至不允许创建它。有没有一种方法可以使用这些值来创建它?

您不能将无效日期强加到 System.DateTime 中。 看看这里:https://docs.microsoft.com/en-us/dotnet/api/system.datetime?view=netframework-4.8

为什么不使用 Date.IsLeapYear(1900) 检查应该设置哪个日期值?

这里有 2 个例子:

    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

DateTime 基本上是一个数字的包装器。您不能将不正确的日期强制输入其中,就像您不能将错误的数字强制输入整数一样。它具有的任何值都代表某个有效日期。因此,即使您可以使用 new Date(1900, 2, 30) 并且没有出现异常,结果也不会是 1900 年 2 月 30 日,而是其他一些有效日期。

DateTime 中有很多有趣的方法。

Private Function GetLastDayInFebruary(YearToTest As Integer) As Integer
    Return Date.DaysInMonth(YearToTest, 2)
End Function