In C#, how do I calculate someone's age based on a DateTime type birthday?

后端 未结 30 2174
名媛妹妹
名媛妹妹 2020-11-21 05:14

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

30条回答
  •  醉梦人生
    2020-11-21 05:42

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

提交回复
热议问题