I need to make a program where you enter the current date and the user's date of birth and it gives you the user's age in days. I have seen this work for years, but days and months do not seem to work. Help would be much appreciated.
Asked
Active
Viewed 1,821 times
2 Answers
2
the user's age in days
You can use TimeSpan.Days
Dim span As TimeSpan = currentDate - birthDate
Dim days As Int32 = span.Days
For example with my birthdate:
Dim currentDate = Date.Now
Dim birthDate = New DateTime(1973, 7, 3)
Dim span As TimeSpan = currentDate - birthDate
Dim days As Int32 = span.Days ' => 14870 omg

Tim Schmelter
- 450,073
- 74
- 686
- 939
-
Sorry, but this is not working. I forgot to mention, I am using VB 2008 Express Edition. Thanks for trying to help though. – DeepSeaProgramming Mar 20 '14 at 12:23
-
@DeepSeaProgramming: no problem with .NET 3.5 (2008): http://msdn.microsoft.com/en-us/library/system.timespan.days%28v=vs.90%29.aspx Do you get an error? – Tim Schmelter Mar 20 '14 at 12:24
-
I need the program to work using the DateTimePicker, and I think I could get it to work, but the picker uses words for the months. Do you know how to fix this? – DeepSeaProgramming Mar 20 '14 at 12:28
-
@DeepSeaProgramming: isn't that a completely different question? Use the `DateTimePicker.Value` property to get the `DateTime`. – Tim Schmelter Mar 20 '14 at 12:30
-
Thanks, got this working now. But is there a way of finding the age in seconds?(the date in ss/mm/hh/dd/mm/yyyy - the dob in dd/mm/yy) – DeepSeaProgramming Mar 27 '14 at 12:10
-
@DeepSeaProgramming: yes, simply use [`TimeSpan.TotalSeconds`](http://msdn.microsoft.com/en-us/library/system.timespan.totalseconds.aspx), so `span.TotalSeconds`. – Tim Schmelter Mar 27 '14 at 12:12
-
@DeepSeaProgramming: what have you tried? A `TimeSpan` has a `TotalSeconds` property. Maybe you have tried `DateTime.TotalSeconds` which does not exist. However, consider to accept the answer :) – Tim Schmelter Mar 27 '14 at 12:17
0
Refer this: A Simple Age Calculator Using VB.Net
Code snippet:
Public Class Form1
Dim dt1 As Date
Dim dt2 As Date
Dim dt3 As TimeSpan
Dim diff As Double
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
dt1 = Me.DateTimePicker1.Value.ToShortDateString
dt2 = Me.DateTimePicker2.Value.ToShortDateString
dt3 = (dt2 - dt1)
diff = dt3.Days
Me.Label1.Text = ("Your Age is " + Str(Int(diff / 365)) + " Year ")
diff = diff Mod 365
Me.Label1.Text = Me.Label1.Text + (Str(Int(diff / 30)) + " Month(s)")
diff = diff Mod 30
Me.Label1.Text = Me.Label1.Text + (Str(diff) + " Day(s)")
End Sub
End Class
Use TimeSpan.Days
to get time passed from DOB to current date and apply simple formulas to get your desired result.
References:
compute age from given birthdate

Community
- 1
- 1

Niranjan Singh
- 18,017
- 2
- 42
- 75