如何使用 datediff 在 DATE 中添加闰年

how to add leapyear in DOB using datediff

我正在使用 datediff 来显示 dateofbirth。任何人都可以帮助我如何以及在何处添加 msgbox("Sorry, INVALID date of BIRTH")?

这是我的代码,在没有 messagebox.

的情况下出现错误
 Dim i As New Integer

Private Function IsLeapYear(ByVal intYear As Integer) As Boolean
    IsLeapYear = (Month(DateSerial(i, 2, 29)) = 2)
End Function


Private Sub ComboMonth_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cboMonth.SelectedIndexChanged
    '   cboMonth.Items.Clear()

    If Me.cboMonth.Text = "February" Then
        For i = 1 To 28
            cboDay.Items.Add(i)
        Next

    ElseIf Me.cboMonth.Text = "January" Or Me.cboMonth.Text = "March" Or Me.cboMonth.Text = "May" Or Me.cboMonth.Text = "July" Or Me.cboMonth.Text = "September" Or Me.cboMonth.Text = "November" Then
        For i = 1 To 31
            cboDay.Items.Add(i)
        Next
    ElseIf Me.cboMonth.Text = "April" Or Me.cboMonth.Text = "June" Or Me.cboMonth.Text = "August" Or Me.cboMonth.Text = "October" Or Me.cboMonth.Text = "December" Then
        For i = 1 To 30
            cboDay.Items.Add(i)
        Next
    End If
End Sub


Private Sub cboYear_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cboYear.SelectedIndexChanged
    Dim dob As Date
    Dim today As Long
  dob = Me.cboMonth.Text & "-" & Me.cboDay.Text & "-" & Me.cboYear.Text 'here error says date is not valid
    today = DateDiff(DateInterval.Day, dob, Now) / 365
    Me.txtAge.Text = today
End Sub

Sub years()
    For i = 1950 To 2050
        cboYear.Items.Add(i)
    Next
End Sub

Sub days()
    For i = 1 To 31
        cboDay.Items.Add(i)
    Next
End Sub

为了回答您的问题,这里提供了一种处理日期转换失败的方法:

    Dim dateAsText as String = Me.cboMonth.Text & "-" & Me.cboDay.Text & "-" & Me.cboYear.Text
    If Not Date.TryParse(dateAsText, dob) Then
       'handle what to do if not converted to date
    Else
       'continue with coding...
    End If

另一方面,您可能想看看结果的准确性。连续几天做数学运算并除以 365 会随着时间的推移从闰年继承一些错误。但是如何计算年龄是另外一个问题,如果你想看那个...