从Years.Months格式的DateTime计算年龄?

gre*_*kes 8 c# algorithm

有没有人在c#中有一个算法来准确计算给定DateTime格式的年龄,其格式为Years.Months?

例如.

  • DOB:1988年9月6日
  • 答案:23.4

  • DOB:1991年3月31日

  • 答案:20.10

  • DOB:1991年2月25日

  • 答案:20.11

谢谢

Jon*_*eet 12

你可以很容易地在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);
    }
}
Run Code Online (Sandbox Code Playgroud)

用做它只是 .NET的DateTime支持将是可能的,但你必须自己做算术,基本上.它几乎肯定不会那么清楚.不是我有偏见或任何东西:)