#### How to calculate age in c#?

Total Post:108

Points:756
1648  View(s)
Ratings:
Rate this:
How to calculate age from DOB
` class Personal{ public DateTime DateOfBirth { get; set; } public string Age { get; set; } }        Personal per=new Personal();       Console.WriteLine("Enter the Date Of Birth :",per.DateOfBirth);         per.DateOfBirth = DateTime.Parse(Console.ReadLine()); public string GetAge(DateTime DateOfBirth)         {        }`
How can i write for function to calculate age from DOB and display
`       Console.WriteLine("The DOB is" +DateOfBirth);       Console.WriteLine("the Age is ...." +Age);DOB is 04/02/1994`
i want display age is 19 years, 6 months, and 9 days
1. Post:110

Points:776
##### Re: How to calculate age in c#?

try this code

ex:

`using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace IfExample{  class DateTimeExtensions  {  public  string ToAgeString( DateTime dob)  {  DateTime dt = DateTime.Now;  int days = dt.Day - dob.Day;  if (days < 0)  {  dt = dt.AddMonths(-1);  days += DateTime.DaysInMonth(dt.Year, dt.Month);  }  int months = dt.Month - dob.Month;  if (months < 0)  {  dt = dt.AddYears(-1);  months += 12;  }  int years = dt.Year - dob.Year;  return string.Format("{0} year{1}, {2} month{3} and {4} day{5}",  years, (years == 1) ? "" : "s",  months, (months == 1) ? "" : "s",  days, (days == 1) ? "" : "s");  }  static void Main()  {  DateTimeExtensions obj = new DateTimeExtensions();  Console.WriteLine("Enter your date of birth in mm/dd/yyyy format to calculate age");  DateTime dob = DateTime.Parse(Console.ReadLine());  string s = obj.ToAgeString(dob);  Console.WriteLine(s);  Console.ReadLine();  }  }}`

Modified On Apr-06-2018 01:14:06 AM

#### CONTACT INFO

10-B Taskand Marg, Near Patrika Chauraha, Civil Lines, Prayagraj, UP, India-211001.
contact@mindstick.com
91-532-2400505

969-G Edgewater Blvd,Suite
793 Foster City-94404, CA (USA)
+1-650-242-0133