有没有人在C#中有一种算法,可以准确地计算给定DateTime格式为Years.Months的年龄?
例如。
谢谢
最佳答案
您可以在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/