如何使用datediff在DATE添加闰年

时间:2015-03-03 18:43:30

标签: vb.net msdn

我使用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

1 个答案:

答案 0 :(得分:0)

要回答您的问题,以下是处理转换失败的一种方法:

    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除了闰年会有一些继承错误。但是,如果你想看看年龄,如何计算年龄是一个不同的问题......