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

后端 未结 30 2110
名媛妹妹
名媛妹妹 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: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);
    

提交回复
热议问题