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

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

    This is not a direct answer, but more of a philosophical reasoning about the problem at hand from a quasi-scientific point of view.

    I would argue that the question does not specify the unit nor culture in which to measure age, most answers seem to assume an integer annual representation. The SI-unit for time is second, ergo the correct generic answer should be (of course assuming normalized DateTime and taking no regard whatsoever to relativistic effects):

    var lifeInSeconds = (DateTime.Now.Ticks - then.Ticks)/TickFactor;
    

    In the Christian way of calculating age in years:

    var then = ... // Then, in this case the birthday
    var now = DateTime.UtcNow;
    int age = now.Year - then.Year;
    if (now.AddYears(-age) < then) age--;
    

    In finance there is a similar problem when calculating something often referred to as the Day Count Fraction, which roughly is a number of years for a given period. And the age issue is really a time measuring issue.

    Example for the actual/actual (counting all days "correctly") convention:

    DateTime start, end = .... // Whatever, assume start is before end
    
    double startYearContribution = 1 - (double) start.DayOfYear / (double) (DateTime.IsLeapYear(start.Year) ? 366 : 365);
    double endYearContribution = (double)end.DayOfYear / (double)(DateTime.IsLeapYear(end.Year) ? 366 : 365);
    double middleContribution = (double) (end.Year - start.Year - 1);
    
    double DCF = startYearContribution + endYearContribution + middleContribution;
    

    Another quite common way to measure time generally is by "serializing" (the dude who named this date convention must seriously have been trippin'):

    DateTime start, end = .... // Whatever, assume start is before end
    int days = (end - start).Days;
    

    I wonder how long we have to go before a relativistic age in seconds becomes more useful than the rough approximation of earth-around-sun-cycles during one's lifetime so far :) Or in other words, when a period must be given a location or a function representing motion for itself to be valid :)

提交回复
热议问题