Calculating age from DOB

  • Thread starter Thread starter John
  • Start date Start date
John said:
Hi

How can I calculate age from a given DOB?

Thanks

Regards

I would use something akin to the following:

Sub Main()
Dim DOB As Date = New Date(1925, 8, 4) ' use your favorite date
Dim Today As Date = Date.Now

Dim age As Integer = Today.Year - DOB.Year

If (Today.Month < DOB.Month) Then age = age - 1
If (Today.Month = DOB.Month) And (Today.Day < DOB.Day) Then _
age = age - 1

Console.WriteLine("Age: " & age)

Console.ReadLine()
End Sub


Hope this helps...
 
=?Utf-8?B?RmFtaWx5IFRyZWUgTWlrZQ==?=
I would use something akin to the following:

Sub Main()
Dim DOB As Date = New Date(1925, 8, 4) ' use your favorite date
Dim Today As Date = Date.Now

Dim age As Integer = Today.Year - DOB.Year

If (Today.Month < DOB.Month) Then age = age - 1
If (Today.Month = DOB.Month) And (Today.Day < DOB.Day) Then _
age = age - 1

Console.WriteLine("Age: " & age)

Console.ReadLine()
End Sub


Hope this helps...

Can you just go Now.Subtract(DOB).Year?
 
Family said:
That was my first thought, but my TimeSpan object doesn't have a Year
property. :(

Probably just as well, it wouldn't know how many years X number of days is
anyway. :(

If you want a one line version, and don't mind adding a boolean expression, you
could write

Dim age As Integer = Now.Year - DOB.Year + (New Date(Now.Year, DOB.Month,
DOB.Day) > Now)
 
Probably just as well, it wouldn't know how many years X number of days is
anyway. :(

If you want a one line version, and don't mind adding a boolean expression, you
could write

Dim age As Integer = Now.Year - DOB.Year + (New Date(Now.Year, DOB.Month,
DOB.Day) > Now)

And this compiles with option strict on? It makes no sense to add a
boolean to an integer!

Chris
 
Chris said:
And this compiles with option strict on? It makes no sense to add a
boolean to an integer!

For option strict, you would need
Dim age As Integer = Now.Year - DOB.Year + CInt(New Date(Now.Year,
DOB.Month, DOB.Day) > Now)

I didn't say I would go about adding booleans to integers, only that you could
if you wanted it all in one expression.;-)
 
Back
Top