是否有人在c#中有一种算法来精确地计算给定DateTime格式的年龄( Years.Months )?
例如:
谢谢
发布于 2012-02-03 12:04:21
您可以很容易地在野田时间中做到这一点:
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
支持就可以做到这一点,但基本上您必须自己做算法。几乎可以肯定的是,情况就不那么明朗了。不是说我有偏见什么的
发布于 2015-02-10 15:56:10
此方法不需要任何外部库:
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);
}
发布于 2012-02-03 12:14:16
var date=new DateTime(DateTime.Now.Subtract(new DateTime(1988,10,31)).Ticks);
Console.WriteLine((date.Year-1).ToString()+"."+(date.Month-1).ToString());
https://stackoverflow.com/questions/9128282
复制相似问题