简体   繁体   English

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

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

Does anyone have an algorithm in c# to accurately calculate an age given a DateTime in the format Years.Months? 有没有人在c#中有一个算法来准确计算给定DateTime格式的年龄,其格式为Years.Months?

eg. 例如。

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

  • DOB: 31-Mar-1991 DOB:1991年3月31日

  • Answer: 20.10 答案:20.10

  • DOB: 25-Feb-1991 DOB:1991年2月25日

  • Answer: 20.11 答案:20.11

thanks 谢谢

You can do this in Noda Time fairly easily: 你可以很容易地在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);
    }
}

Doing it with just .NET's DateTime support would be possible, but you'd have to do the arithmetic yourself, basically. 只使用 .NET的DateTime支持就可以了,但基本上你必须自己做算术。 And it almost certainly wouldn't be as clear. 它几乎肯定不会那么清楚。 Not that I'm biased or anything :) 不是我有偏见或任何东西:)

This method doesn't require any external libraries: 此方法不需要任何外部库:

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