Given a DateTime representing a person's birthday, how do I calculate their age?
Given a DateTime representing a person's birthday, how do I calculate their age?
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 = 280111Drop the last 4 digits = 28. C# Code:
var now = float.Parse(DateTime.Now.ToString("yyyy.MMdd")); var dob = float.Parse(dateOfBirth.ToString("yyyy.MMdd")); var age = (int)(now - dob);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; }
Please login in order to answer a question