给定代表某人生日的DateTime,我如何计算他们的年龄(以年为单位)?
当前回答
这里有一个DateTime扩展程序,它将年龄计算添加到DateTime对象。
public static class AgeExtender
{
public static int GetAge(this DateTime dt)
{
int d = int.Parse(dt.ToString("yyyyMMdd"));
int t = int.Parse(DateTime.Today.ToString("yyyyMMdd"));
return (t-d)/10000;
}
}
其他回答
这是一个非常简单的方法:
int Age = DateTime.Today.Year - new DateTime(2000, 1, 1).Year;
我对DateTime一无所知,但我能做的就是:
using System;
public class Program
{
public static int getAge(int month, int day, int year) {
DateTime today = DateTime.Today;
int currentDay = today.Day;
int currentYear = today.Year;
int currentMonth = today.Month;
int age = 0;
if (currentMonth < month) {
age -= 1;
} else if (currentMonth == month) {
if (currentDay < day) {
age -= 1;
}
}
currentYear -= year;
age += currentYear;
return age;
}
public static void Main()
{
int ageInYears = getAge(8, 10, 2007);
Console.WriteLine(ageInYears);
}
}
有点困惑,但仔细看代码,这一切都是有意义的。
要使用最近的年龄计算年龄:
var ts = DateTime.Now - new DateTime(1988, 3, 19);
var age = Math.Round(ts.Days / 365.0);
我创建了一个Age结构,如下所示:
public struct Age : IEquatable<Age>, IComparable<Age>
{
private readonly int _years;
private readonly int _months;
private readonly int _days;
public int Years { get { return _years; } }
public int Months { get { return _months; } }
public int Days { get { return _days; } }
public Age( int years, int months, int days ) : this()
{
_years = years;
_months = months;
_days = days;
}
public static Age CalculateAge( DateTime dateOfBirth, DateTime date )
{
// Here is some logic that ressembles Mike's solution, although it
// also takes into account months & days.
// Ommitted for brevity.
return new Age (years, months, days);
}
// Ommited Equality, Comparable, GetHashCode, functionality for brevity.
}
这里有一个单行线:
int age = new DateTime(DateTime.Now.Subtract(birthday).Ticks).Year-1;