Bojensen Blogs

Calculate a Persons Age (VB.NET/ASP.NET)

Her er en lille metode i VB.NET, som kan beregne en persons alder i år

1 Public Function GetAge(ByVal Birthdate As System.DateTime, _ 2 Optional ByVal AsOf As System.DateTime = #1/1/1700#) _ 3 As String 4 5 'Don't set second parameter if you want Age as of today 6 7 'Demo 1: get age of person born 2/11/1954 8 'Dim objDate As New System.DateTime(1954, 2, 11) 9 'Debug.WriteLine(GetAge(objDate)) 10 11 'Demo 1: get same person's age 10 years from now 12 'Dim objDate As New System.DateTime(1954, 2, 11) 13 'Dim objdate2 As System.DateTime 14 'objdate2 = Now.AddYears(10) 15 'Debug.WriteLine(GetAge(objDate, objdate2)) 16 17 Dim iMonths As Integer 18 Dim iYears As Integer 19 Dim dYears As Decimal 20 Dim lDayOfBirth As Long 21 Dim lAsOf As Long 22 Dim iBirthMonth As Integer 23 Dim iAsOFMonth As Integer 24 25 If AsOf = "#1/1/1700#" Then 26 AsOf = DateTime.Now 27 End If 28 lDayOfBirth = DatePart(DateInterval.Day, Birthdate) 29 lAsOf = DatePart(DateInterval.Day, AsOf) 30 31 iBirthMonth = DatePart(DateInterval.Month, Birthdate) 32 iAsOFMonth = DatePart(DateInterval.Month, AsOf) 33 34 iMonths = DateDiff(DateInterval.Month, Birthdate, AsOf) 35 36 dYears = iMonths / 12 37 38 iYears = Math.Floor(dYears) 39 40 If iBirthMonth = iAsOFMonth Then 41 If lAsOf < lDayOfBirth Then 42 iYears = iYears - 1 43 End If 44 End If 45 46 Return iYears 47 End Function

Comments are closed.