vb.net编码中的年龄计算

时间:2015-09-13 11:28:58

标签: vb.net

网络编码,我真的陷入了这个基本的年龄计算。我创建了一个表单字段,在组框中它应该显示一个人的年龄。我在代码中面临的最大问题是本月的因素。我已尝试过所有类型,例如使用DateInterval.Month但仍然没有运气。这里MyEntPatient.DOB是患者的DOB

Dim Years As Integer
Dim BDAY As New DateTime(Now.Year)
BDAY = MyEntPatient.DOB
If (BDAY > Now) Then
    Years = DateDiff(DateInterval.Year, MyEntPatient.DOB, Now) - 1
Else
    Years = DateDiff(DateInterval.Year, MyEntPatient.DOB, Now)
End If

Me.gpxPatientDetails.Text = " Age:" + Years.ToString()

2 个答案:

答案 0 :(得分:0)

如果你有更大/更小年龄的问题,因为有人今年没有生日(例如12月出生),你可以试试这个:

Dim bday As New DateTime(2010, 1, 25) 
Dim months As Integer = DateDiff(DateInterval.Month, bday, Now)
Dim years As Integer = months / 12

答案 1 :(得分:0)

Function AgeCalculator(ByVal FromDate As String, Optional flgyearOnly As Boolean = False) As String '23/11/2017
    If Not IsDate(FromDate) Then Return ""
    Dim tmpYear As String = "", tmpMonth As String = "", tmpdiff As Integer = 0
        Dim tmpAge As String = ""
        tmpdiff = DateDiff(DateInterval.Day, CDate(Format2DateMMM(FromDate)), Now)
        If tmpdiff <= 0 Then Return ""
        If tmpdiff > 0 And tmpdiff <= 29 Then
            Return tmpdiff & " Days"
        End If
        If tmpdiff = 30 Then
            Return " 1 Month"
        End If

        tmpYear = tmpdiff / 365
        If InStr(tmpYear, ".") > 0 Then
            tmpYear = Microsoft.VisualBasic.Left(tmpYear, InStr(tmpYear, ".") - 1)
        End If

        If Val(tmpYear) = 0 Then tmpYear = ""
    If Val(tmpYear) > 0 Then
        tmpAge = tmpYear & " years"
        If flgyearOnly Then Return tmpAge
    End If

    tmpdiff = (tmpdiff - (Val(tmpYear) * 365))

        tmpMonth = tmpdiff / 30
        If InStr(tmpMonth, ".") > 0 Then
            tmpMonth = Microsoft.VisualBasic.Left(tmpMonth, InStr(tmpMonth, ".") - 1)
        End If

        If Val(tmpMonth) = 0 Then tmpMonth = ""

        If tmpMonth > 0 Then
        tmpAge &= "  " & tmpMonth & " Months"
    End If

        tmpdiff = (tmpdiff - (Val(tmpMonth) * 30))
        If Val(tmpdiff) > 0 Then
            tmpAge &= "  " & tmpdiff & " Days"
        End If
        Return tmpAge: End Function