Public Function CalculateAge(ByVal BirthDate As Object) As String
'returns a string that show years, months and days
Dim intYear As Integer, intMonth As Integer, intDay As Integer
Dim dtTemp As Date
If Not IsDate(BirthDate) Then Exit Function
dtTemp = CDate(BirthDate)
If dtTemp > Now Then Exit Function
intYear = dtTemp.Year
intMonth = dtTemp.Month
intDay = dtTemp.Day
intYear = Date.Now.Year - intYear
intMonth = Date.Now.Month - intMonth
intDay = Date.Now.Day - intDay
If intDay < 0 Then
Select Case dtTemp.Month
Case 1, 3, 5, 7, 8, 10, 12
intDay = 31 - Math.Abs(intDay)
Case 4, 6, 9, 11
intDay = 30 - Math.Abs(intDay)
Case 2
If dtTemp.Year Mod 4 = 0 Then
intDay = 29 - Math.Abs(intDay)
Else
intDay = 28 - Math.Abs(intDay)
End If
End Select
intMonth = intMonth - 1
End If
If intMonth < 0 Then
intMonth = 12 - Math.Abs(intMonth)
intYear = intYear - 1
End If
Return IIf(intYear <> 0, intYear & " Years ", "") & _
IIf(intMonth <> 0, intMonth & " Months ", "") & _
IIf(intDay <> 0, intDay & " Days", "")
End Function
Public Function CalcAge(ByVal BirthDate As Object) As Long
'returns only years
If Not IsDate(BirthDate) Then Exit Function
Dim dtTemp As Date
dtTemp = CDate(BirthDate)
If dtTemp > Now Then Exit Function
Return DateDiff("yyyy", dtTemp, Date.Now) + (DateSerial(Year(Date.Now), _
Month(dtTemp), dtTemp.Day) >= Date.Now)
End Function
That works but assumes they've had their b'day for that year.ritesh_jain1982 said:txtage.text=DateDiff(DateInterval.Year,cdate(txtdo b.text.trim),Now.Date)
Dim DateNow as date = date.now
Dim DateBorn as date = cdate(txtdob.text)
If DateNow.month < DateBorn.month or DateNow.month = DateBorn.month AND DateNow.day < DateBorn.day Then
DateNow = DateNow.AddYears(-1)
End IF
txtage.text= DateNow.year - DateBorn.year
Or
txtage.text=DateDiff(DateInterval.Year,DateBorn,DateNow)
Kudos for bringing up a 7 year old thread. You can also just subtract the two dates and get a timespan to know how much time as elapsed:as i got from your message, i suppose that u have a a birth date in database with string format and you want to calculate the age, first u need to convert this string to date format and then calculate the age as follows:
Dim strDate As String
Dim objdate As Date
strDate = 'your birthdate from database'
strDate = strDate.Substring(0, 3) & strDate.Substring(3, 3) & strDate.Substring(6, 4) // how saved in database using calendar control for ex. 02/04/1990
objdate = Date.Parse(strDate).ToShortDateString
Dim todayYear As Integer = Date.Now.Year
Dim birthYear As Integer = objdate.Year
Dim age As Integer = todayYear - birthYear
Private Function CalculateAge(ByVal Date1 As Date, ByVal Date2 As Date) As TimeSpan Select Case True Case Date1 > Date2 : Return Date1.Subtract(Date2) Case Else : Return Date2.Subtract(Date1) End Select End Function