Home » Questions » Computers [ Ask a new question ]

c# - How do I calculate someone's age based on a DateTime type birthday? -

"Given a DateTime representing a person's birthday, how do I calculate their age in years?





c# .net datetime












ShareShare a link to this question Copy linkCC BY-SA 4.0



Improve this question




Follow
Follow this question to receive notifications











edited Jan 5 at 17:33
















community wiki




33 revs, 29 users 32%Shaik Raffi"

Asked by: Guest | Views: 358
Total answers/comments: 2
bert [Entry]

"An easy to understand and simple solution.
// Save today's date.
var today = DateTime.Today;

// Calculate the age.
var age = today.Year - birthdate.Year;

// Go back to the year in which the person was born in case of a leap year
if (birthdate.Date > today.AddYears(-age)) age--;

However, this assumes you are looking for the western idea of the age and not using East Asian reckoning."
bert [Entry]

"This is a strange way to do it, but if you format the date to yyyymmdd and subtract the date of birth from the current date then drop the last 4 digits you've got the age :)

I don't know C#, but I believe this will work in any language.

20080814 - 19800703 = 280111

Drop the last 4 digits = 28.

C# Code:

int now = int.Parse(DateTime.Now.ToString(""yyyyMMdd""));
int dob = int.Parse(dateOfBirth.ToString(""yyyyMMdd""));
int age = (now - dob) / 10000;

Or alternatively without all the type conversion in the form of an extension method. Error checking omitted:

public static Int32 GetAge(this DateTime dateOfBirth)
{
var today = DateTime.Today;

var a = (today.Year * 100 + today.Month) * 100 + today.Day;
var b = (dateOfBirth.Year * 100 + dateOfBirth.Month) * 100 + dateOfBirth.Day;

return (a - b) / 10000;
}"