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

后端 未结 30 2090
名媛妹妹
名媛妹妹 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:41

    SQL version:

    declare @dd smalldatetime = '1980-04-01'
    declare @age int = YEAR(GETDATE())-YEAR(@dd)
    if (@dd> DATEADD(YYYY, -@age, GETDATE())) set @age = @age -1
    
    print @age  
    
    0 讨论(0)
  • 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;
    }
    
    0 讨论(0)
  • I've made one small change to Mark Soen's answer: I've rewriten the third line so that the expression can be parsed a bit more easily.

    public int AgeInYears(DateTime bday)
    {
        DateTime now = DateTime.Today;
        int age = now.Year - bday.Year;            
        if (bday.AddYears(age) > now) 
            age--;
        return age;
    }
    

    I've also made it into a function for the sake of clarity.

    0 讨论(0)
  • 2020-11-21 05:45

    Here's a one-liner:

    int age = new DateTime(DateTime.Now.Subtract(birthday).Ticks).Year-1;
    
    0 讨论(0)
  • 2020-11-21 05:45

    This gives "more detail" to this question. Maybe this is what you're looking for

    DateTime birth = new DateTime(1974, 8, 29);
    DateTime today = DateTime.Now;
    TimeSpan span = today - birth;
    DateTime age = DateTime.MinValue + span;
    
    // Make adjustment due to MinValue equalling 1/1/1
    int years = age.Year - 1;
    int months = age.Month - 1;
    int days = age.Day - 1;
    
    // Print out not only how many years old they are but give months and days as well
    Console.Write("{0} years, {1} months, {2} days", years, months, days);
    
    0 讨论(0)
  • 2020-11-21 05:45
    TimeSpan diff = DateTime.Now - birthdayDateTime;
    string age = String.Format("{0:%y} years, {0:%M} months, {0:%d}, days old", diff);
    

    I'm not sure how exactly you'd like it returned to you, so I just made a readable string.

    0 讨论(0)
提交回复
热议问题