0

I'm trying to calculate the age based on the DOB.

Int32 DOB = 19900427;
Int32 current = 20140111;
Int32 result = current - dob;

Now i just need to display the starting 2 digit of the result in a text box. Could you please help me with this?

damienfrancois
  • 52,978
  • 9
  • 96
  • 110
Partha
  • 21
  • 1
  • 1
  • 5
  • Please, read this thread [Date Difference in Years C#](http://stackoverflow.com/questions/4127363/date-difference-in-years-c-sharp). Yo find all you need there. – Roman Izosimov Jan 11 '14 at 17:55

1 Answers1

3

Don't do it that way. Just don't. You can't get a useful age representation by subtracting one value from another - you'll find that the difference between two people who were born a day apart can differ massively based on exactly when those dates are.

For example, consider three people with birth dates of:

A: December 30th 2013 - 20131230
B: December 31st 2013 - 20131231
C: January 1st 2014   - 20140101

That gives a difference between the ages of A and B of 1, but a difference between the ages of B and C of 8870. It's surely not good for you.

Use DateTime to represent dates - or preferably, use LocalDate from my Noda Time library. Then you can determine the difference between the dates however you want - potentially just in a number of days, for example.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • Thanks a lot for your speedy reply. – Partha Jan 11 '14 at 17:51
  • Here is my code : DateTime date = DateTime.Today.Date; Int64 n = Int64.Parse(date.ToString("ddmmyyyy")); SqlConnection con = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\adhar.mdf;Integrated Security=True;User Instance=True;"); con.Open(); SqlCommand cmd = new SqlCommand("select dob from sample Where cardnum = '"+TextBox1.Text+"'"); cmd.ExecuteNonQuery(); Int64 dob = Convert.ToInt32(cmd.ExecuteScalar()); Int64 result = n - dob; – Partha Jan 11 '14 at 17:51
  • @Partha: Why are you doing that at all? Just *don't* use this strange integer representation at all. You're not trying to represent an integer: you're trying to represent a date. SQL Server supports Date fields: use them. Also, use parameterized SQL rather than embedding values directly in the SQL. – Jon Skeet Jan 11 '14 at 17:54
  • Thanks a lot for your advice sir. I finally succeeded in getting the calculating the correct age using datetime. Thanks once again! – Partha Jan 11 '14 at 18:37