This is a really small snippet of code that I have used over and over again.
Imagine you are given date of birth of the person and you have to get the age, how would you go about it?
1. Create a private function and pass it date of birth
2. Subtract the number of years from current year
3. In C#, every day of the year has got a value, an extra check is required to see if the current Day is less than the day the person was born in, for example, if today is 15th of March and the person was born 1st of March, you have to subtract an extra year.
Sample code is given below
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
|private static int CalculateAge(DateTime dateOfBirth)|
|int age = 0;|
|age = DateTime.Now.Year – dateOfBirth.Year;|
|if (DateTime.Now.DayOfYear < dateOfBirth.DayOfYear)|
|age = age – 1;|
7 thoughts on “Calculating age from date of birth – C#”
Please give solution to calculate my age (i.e 20 years, 04 months, 3 weeks, 12 days, 2 hours)
You would probably need to create dob variable which would include time as well. For example, if the person is born on 14th August 1995 at 3:25:45 pm, you can declare
DateTime myDob = new DateTime(1995,08,14,15,25,45);
and then use TimeSpan c# class to find out the exact time difference
TimeSpan interval = DateTime.Now – myDob;
and then apply some formatting to display age as per your requirements.
Thanks Dude 🙂
Thanks, really helped. I modified the code to consider leap years.
private static int CalculateAge(DateTime dateOfBirth)
int age = 0, dayofyr = 0;
//if leap year and past february 28
if (DateTime.IsLeapYear(dateOfBirth.Year) && dateOfBirth.DayOfYear >= 60)
dayofyr = dateOfBirth.DayOfYear – 1;
dayofyr = dateOfBirth.DayOfYear;
age = DateTime.Now.Year – dateOfBirth.Year;
if (DateTime.Now.DayOfYear < dayofyr)
age = age – 1;
I don’t think you have to add leap year check as DayOfYear value is between 1-366 as per MSDN, so if current year is a leap year, 31st December will be 366th day. Please check sample code given at https://msdn.microsoft.com/en-us/library/system.datetime.dayofyear(v=vs.110).aspx
That’s precisely why you need to add a leap year check.
If my birthday is April 2nd of a leap year, then it’s the 93rd day of the year. But if it’s currently April 2nd of a non-leap year then it’s the 92nd day and the math would subtract 1 when it shouldn’t. It also works the other way.
If my birthday is April 2nd of a non-leap year, then it’s the 92nd day. But if it’s currently April 1st of a leap year then that is also the 92nd day and it would not subtract 1 when it should.
You need to take the leap year check in to consideration if some one is born on Feb 29. Your implementation will output wrong age if some one is born on Feb 29, checking his age on non leap year after Feb 28.