簡體   English   中英

從Years.Months格式的DateTime計算年齡?

[英]Calculate an age from a DateTime in Years.Months format?

有沒有人在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支持就可以了,但基本上你必須自己做算術。 它幾乎肯定不會那么清楚。 不是我有偏見或任何東西:)

此方法不需要任何外部庫:

private static string AgeInYearsMonths(DateTime? DateOfBirth)
{
    if (DateOfBirth == null) return "";
    if (DateOfBirth >= DateTime.Today)
        throw new ArgumentException("DateOfBirth cannot be in future!");

    DateTime d = DateOfBirth.Value;
    int monthCount = 0;
    while ((d = d.AddMonths(1)) <= DateTime.Today)
    {
        monthCount++;
    }
    return string.Format("{0}.{1}", monthCount / 12, monthCount % 12);
}
var date=new DateTime(DateTime.Now.Subtract(new DateTime(1988,10,31)).Ticks);
Console.WriteLine((date.Year-1).ToString()+"."+(date.Month-1).ToString());

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM