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

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

    This classic question is deserving of a Noda Time solution.

    static int GetAge(LocalDate dateOfBirth)
    {
        Instant now = SystemClock.Instance.Now;
    
        // The target time zone is important.
        // It should align with the *current physical location* of the person
        // you are talking about.  When the whereabouts of that person are unknown,
        // then you use the time zone of the person who is *asking* for the age.
        // The time zone of birth is irrelevant!
    
        DateTimeZone zone = DateTimeZoneProviders.Tzdb["America/New_York"];
    
        LocalDate today = now.InZone(zone).Date;
    
        Period period = Period.Between(dateOfBirth, today, PeriodUnits.Years);
    
        return (int) period.Years;
    }
    

    Usage:

    LocalDate dateOfBirth = new LocalDate(1976, 8, 27);
    int age = GetAge(dateOfBirth);
    

    You might also be interested in the following improvements:

    • Passing in the clock as an IClock, instead of using SystemClock.Instance, would improve testability.

    • The target time zone will likely change, so you'd want a DateTimeZone parameter as well.

    See also my blog post on this subject: Handling Birthdays, and Other Anniversaries

提交回复
热议问题