Avatar
7718 reputation
Posted on:28 Aug '16 - 10:37
54

How do I calculate someone's age in C#?

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

C#

Answers

88
This answer is accepted

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:
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;
}

Avatar
7979 reputation
Posted on:28 Aug '16 - 11:13

Please login in order to answer a question