-1

I am a VB.NET beginner and i would like to ask how one can calculate age of a person if only the year of birth is entered in a text box in a form. I am supposed to use the current year minus the year of birth but i don't really have the code. here is the problem : there is a text box named txtdob in a form where the user is required to enter his/her year of birth. I need a code that determines the age of the user using the current YEAR and the year of birth entered.

Das Sir
  • 13
  • 1
  • 3
  • Here are a couple of examples: http://stackoverflow.com/questions/9/how-do-i-calculate-someones-age http://stackoverflow.com/questions/2194999/how-to-calculate-an-age-based-on-a-birthday – Mark Redman Jul 25 '13 at 07:45
  • @MarkRedman: These questions both calculate the age from two `DateTimes` (in C#), OP wants to calculate it from an `Integer`(year of birth) and he is also a beginner. – Tim Schmelter Jul 25 '13 at 07:55
  • I see you are receiving some negative votes here, let me explain why. You should try to ask your question from a point of view that shows you have already actually thought about "what you WANT" to do, but cant get it working. What you are doing here, is asking someone to do your assignment FOR you. A good example would be to have rather asked. I have researched dates in .net, but I cant seem to figure out how to subtract one date from another, and get the total amount of years... (and then showing some code of what you have tried...) – Louis van Tonder Jul 25 '13 at 07:56

4 Answers4

1

Use TimeSpan .. Do substract Now to Your Date ..

Dim dBirth as Date
Dim nDiff as TimeSpan

dBirth = ........  ' you fill with yours

nDiff = Now.Substract(dBirth)

Msgbox( format(nDiff.Days/365) ) '--------> will show the age ..
matzone
  • 5,703
  • 3
  • 17
  • 20
0

Use Integer.Parse or Integer.TryParse and then calculate it from Date.Now:

Dim birthYear As Int32
If Int32.TryParse(txtAge.Text, birthYear) Then
    Dim age As Int32 = Date.Now.Year - birthYear
    MessageBox.Show("Your age is: " & age)
Else
    MessageBox.Show("Please enter a valid year of birth")
End If
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
0

Have not tested this, but it should get you going...

yyyy is the birth year....

now.subtract(cdate("0/0/yyyy")).totalyears

Cheers

Louis van Tonder
  • 3,664
  • 3
  • 31
  • 62
0

Have a look at the DateDiff function. It tells you the difference between two dates, and you can specify the DateInterval to be Year, eg

Dim difference As Int = DateDiff(DateInterval.Year, dateOfBirth, currentDate)

Link to the resource: http://msdn.microsoft.com/en-us/library/b5xbyt6f(v=vs.80).aspx

Slava
  • 48
  • 6