有没有人在C#中有一种算法,可以准确地计算给定DateTime格式为Years.Months的年龄?

例如。

  • DOB:1988年9月6日
  • 答案:23.4
  • DOB:1991年3月31日
  • 答案:20.10
  • DOB:1991年2月25日
  • 答案:20.11

  • 谢谢

    最佳答案

    您可以在Noda Time中轻松完成此操作:

    using System;
    using NodaTime;
    
    class Test
    {
        static void Main()
        {
            ShowAge(1988, 9, 6);
            ShowAge(1991, 3, 31);
            ShowAge(1991, 2, 25);
        }
    
        private static readonly PeriodType YearMonth =
            PeriodType.YearMonthDay.WithDaysRemoved();
    
        static void ShowAge(int year, int month, int day)
        {
            var birthday = new LocalDate(year, month, day);
            // For consistency for future readers :)
            var today = new LocalDate(2012, 2, 3);
    
            Period period = Period.Between(birthday, today, YearMonth);
            Console.WriteLine("Birthday: {0}; Age: {1} years, {2} months",
                              birthday, period.Years, period.Months);
        }
    }
    

    仅使用.NET的DateTime支持就可以做到这一点,但是基本上,您必须自己做算法。而且几乎肯定不会那么清楚。并不是说我有偏见或其他:)

    关于c# - 从DateTime以Years.Months格式计算年龄?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/9128282/

    10-11 08:09