When working in any application many times we want to get the current age of a person from date of birth.We can easily implement this functionality in C# using the Substract method of DateTime class.

To Calculate age from DateofBirth in C# we need to use the DateTime type and Math class.

In the following example we are using the Round() method of the Math class to convert the years from the total number of days.We are calculating the total number of days using the TotalDays property of TimeSpan data type.

1 2 3 4 5 6 7 8 9 10 11 | private static void GetAgeFromDateofBirth(int year,int month,int day) { var today = DateTime.Today; // Calculate the age. DateTime birthdate = new DateTime(1978, 7, 26); var age = today.Subtract(birthdate).TotalDays; var years = (age / 365); Math.Round(years); } |

## Leave a Reply