如何计算某个人在给定日期的年龄?
我有出生日期,而我现在正在做的事情,我想要计算它的日期是年末,例如31/12/2012 23:59:59。
我如何根据这些变量计算出一个人年底的年龄?
感谢。
答案 0 :(得分:1)
减去目标日期和出生日期的年份;如果目标日期在该年的出生日期之前,则减去1年。
答案 1 :(得分:1)
DateTime birthDayPersonA = new DateTime(1986,12,1);
DateTime givenDate = new DateTime(2012,12,24);
TimeSpan age = givenDate.Substract(birthDayPersonA);
答案 2 :(得分:1)
您可以执行以下操作:
答案 3 :(得分:0)
var age = new Timespan(endOfYearDate.Ticks - dateOfBirth.Ticks).TotalDays();
或者只是几天,如果你想让它围绕你。
注意您需要将天数转换为年数除以365.25
答案 4 :(得分:0)
var birthday = new DateTime(1973, 7, 10);
var date = new DateTime(2012, 12, 31);
TimeSpan span = date - birthday;
DateTime age = DateTime.MinValue + span;
// MinValue is 1/1/1 so we have to subtract one year
int yearsOfAge = age.Year - 1;
答案 5 :(得分:0)
public enum DateInterval
{
Day,
DayOfYear,
Hour,
Minute,
Month,
Quarter,
Second,
Weekday,
WeekOfYear,
Year
}
public class DateAndTime
{
public static long DateDiff(DateInterval interval, DateTime dt1, DateTime dt2)
{
return DateDiff(interval, dt1, dt2, System.Globalization.DateTimeFormatInfo.CurrentInfo.FirstDayOfWeek);
}
private static int GetQuarter(int nMonth)
{
if (nMonth <= 3)
return 1;
if (nMonth <= 6)
return 2;
if (nMonth <= 9)
return 3;
return 4;
}
public static long DateDiff(DateInterval interval, DateTime dt1, DateTime dt2, DayOfWeek eFirstDayOfWeek)
{
if (interval == DateInterval.Year)
return dt2.Year - dt1.Year;
if (interval == DateInterval.Month)
return (dt2.Month - dt1.Month) + (12 * (dt2.Year - dt1.Year));
TimeSpan ts = dt2 - dt1;
if (interval == DateInterval.Day || interval == DateInterval.DayOfYear)
return Round(ts.TotalDays);
if (interval == DateInterval.Hour)
return Round(ts.TotalHours);
if (interval == DateInterval.Minute)
return Round(ts.TotalMinutes);
if (interval == DateInterval.Second)
return Round(ts.TotalSeconds);
if (interval == DateInterval.Weekday)
{
return Round(ts.TotalDays / 7.0);
}
if (interval == DateInterval.WeekOfYear)
{
while (dt2.DayOfWeek != eFirstDayOfWeek)
dt2 = dt2.AddDays(-1);
while (dt1.DayOfWeek != eFirstDayOfWeek)
dt1 = dt1.AddDays(-1);
ts = dt2 - dt1;
return Round(ts.TotalDays / 7.0);
}
if (interval == DateInterval.Quarter)
{
double d1Quarter = GetQuarter(dt1.Month);
double d2Quarter = GetQuarter(dt2.Month);
double d1 = d2Quarter - d1Quarter;
double d2 = (4 * (dt2.Year - dt1.Year));
return Round(d1 + d2);
}
return 0;
}
private static long Round(double dVal)
{
if (dVal >= 0)
return (long)Math.Floor(dVal);
return (long)Math.Ceiling(dVal);
}
}
用法是
public long HowOldAmIToday(DateTime DOB)
{
return DateAndTime.DateDiff(DateInterval.Year, DOB, DateTime.Today);
}