public static int GetAge(DateTime birthDate){DateTime n = DateTime.Now; // To avoid a race condition around midnightint age = n.Year - birthDate.Year;
if (n.Month < birthDate.Month || (n.Month == birthDate.Month && n.Day < birthDate.Day))age--;
return age;}
// Save today's date.var today = DateTime.Today;
// Calculate the age.var age = today.Year - birthdate.Year;
// Go back to the year in which the person was born in case of a leap yearif (birthdate.Date > today.AddYears(-age)) age--;
using System;using System.Data;using System.Data.Sql;using System.Data.SqlClient;using System.Data.SqlTypes;using Microsoft.SqlServer.Server;
public partial class UserDefinedFunctions{[SqlFunction(DataAccess = DataAccessKind.Read)]public static SqlInt32 CalculateAge(string strBirthDate){DateTime dtBirthDate = new DateTime();dtBirthDate = Convert.ToDateTime(strBirthDate);DateTime dtToday = DateTime.Now;
// get the difference in yearsint years = dtToday.Year - dtBirthDate.Year;
// subtract another year if we're before the// birth day in the current yearif (dtToday.Month < dtBirthDate.Month || (dtToday.Month == dtBirthDate.Month && dtToday.Day < dtBirthDate.Day))years=years-1;
int intCustomerAge = years;return intCustomerAge;}};
public void LoopAge(DateTime myDOB, DateTime FutureDate){int years = 0;int months = 0;int days = 0;
DateTime tmpMyDOB = new DateTime(myDOB.Year, myDOB.Month, 1);
DateTime tmpFutureDate = new DateTime(FutureDate.Year, FutureDate.Month, 1);
while (tmpMyDOB.AddYears(years).AddMonths(months) < tmpFutureDate){months++;
if (months > 12){years++;months = months - 12;}}
if (FutureDate.Day >= myDOB.Day){days = days + FutureDate.Day - myDOB.Day;}else{months--;
if (months < 0){years--;months = months + 12;}
days +=DateTime.DaysInMonth(FutureDate.AddMonths(-1).Year, FutureDate.AddMonths(-1).Month) + FutureDate.Day - myDOB.Day;
}
//add an extra day if the dob is a leap dayif (DateTime.IsLeapYear(myDOB.Year) && myDOB.Month == 2 && myDOB.Day == 29){//but only if the future date is less than 1st Marchif (FutureDate >= new DateTime(FutureDate.Year, 3, 1))days++;}
}
public int CalculateAgeWrong1(DateTime birthDate, DateTime now){return new DateTime(now.Subtract(birthDate).Ticks).Year - 1;}
public int CalculateAgeWrong2(DateTime birthDate, DateTime now){int age = now.Year - birthDate.Year;
if (now < birthDate.AddYears(age))age--;
return age;}
public int CalculateAgeCorrect(DateTime birthDate, DateTime now){int age = now.Year - birthDate.Year;
if (now.Month < birthDate.Month || (now.Month == birthDate.Month && now.Day < birthDate.Day))age--;
return age;}
public int CalculateAgeCorrect2(DateTime birthDate, DateTime now){int age = now.Year - birthDate.Year;
// For leap years we need thisif (birthDate > now.AddYears(-age))age--;// Don't use:// if (birthDate.AddYears(age) > now)// age--;
return 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.}
public string LoopAge(DateTime myDOB, DateTime FutureDate){int years = 0;int months = 0;int days = 0;
DateTime tmpMyDOB = new DateTime(myDOB.Year, myDOB.Month, 1);
DateTime tmpFutureDate = new DateTime(FutureDate.Year, FutureDate.Month, 1);
while (tmpMyDOB.AddYears(years).AddMonths(months) < tmpFutureDate){months++;if (months > 12){years++;months = months - 12;}}
if (FutureDate.Day >= myDOB.Day){days = days + FutureDate.Day - myDOB.Day;}else{months--;if (months < 0){years--;months = months + 12;}days = days + (DateTime.DaysInMonth(FutureDate.AddMonths(-1).Year, FutureDate.AddMonths(-1).Month) + FutureDate.Day) - myDOB.Day;
}
//add an extra day if the dob is a leap dayif (DateTime.IsLeapYear(myDOB.Year) && myDOB.Month == 2 && myDOB.Day == 29){//but only if the future date is less than 1st Marchif(FutureDate >= new DateTime(FutureDate.Year, 3,1))days++;}
return "Years: " + years + " Months: " + months + " Days: " + days;}
public static class DateTimeExtensions{public static int Age(this DateTime birthDate){return Age(birthDate, DateTime.Now);}
public static int Age(this DateTime birthDate, DateTime offsetDate){int result=0;result = offsetDate.Year - birthDate.Year;
if (offsetDate.DayOfYear < birthDate.DayOfYear){result--;}
return result;}}
public int AgeInYears(DateTime birthDate, DateTime referenceDate){Debug.Assert(referenceDate >= birthDate,"birth date must be on or prior to the reference date");
DateTime birth = birthDate.Date;DateTime reference = referenceDate.Date;int years = (reference.Year - birth.Year);
//// an offset of -1 is applied if the birth date has// not yet occurred in the current year.//if (reference.Month > birth.Month);else if (reference.Month < birth.Month)--years;else // in birth month{if (reference.Day < birth.Day)--years;}
return years ;}
public static class DateTimeExtensions{/// <summary>/// Calculates the age in years of the current System.DateTime object today./// </summary>/// <param name="birthDate">The date of birth</param>/// <returns>Age in years today. 0 is returned for a future date of birth.</returns>public static int Age(this DateTime birthDate){return Age(birthDate, DateTime.Today);}
/// <summary>/// Calculates the age in years of the current System.DateTime object on a later date./// </summary>/// <param name="birthDate">The date of birth</param>/// <param name="laterDate">The date on which to calculate the age.</param>/// <returns>Age in years on a later day. 0 is returned as minimum.</returns>public static int Age(this DateTime birthDate, DateTime laterDate){int age;age = laterDate.Year - birthDate.Year;
if (age > 0){age -= Convert.ToInt32(laterDate.Date < birthDate.Date.AddYears(age));}else{age = 0;}
return age;}}
现在,运行这个测试:
class Program{static void Main(string[] args){RunTest();}
private static void RunTest(){DateTime birthDate = new DateTime(2000, 2, 28);DateTime laterDate = new DateTime(2011, 2, 27);string iso = "yyyy-MM-dd";
for (int i = 0; i < 3; i++){for (int j = 0; j < 3; j++){Console.WriteLine("Birth date: " + birthDate.AddDays(i).ToString(iso) + " Later date: " + laterDate.AddDays(j).ToString(iso) + " Age: " + birthDate.AddDays(i).Age(laterDate.AddDays(j)).ToString());}}
Console.ReadKey();}}
关键日期的例子是这样的:
出生日期:2000-02-29后来日期:2011-02-28年龄:11
输出:
{Birth date: 2000-02-28 Later date: 2011-02-27 Age: 10Birth date: 2000-02-28 Later date: 2011-02-28 Age: 11Birth date: 2000-02-28 Later date: 2011-03-01 Age: 11Birth date: 2000-02-29 Later date: 2011-02-27 Age: 10Birth date: 2000-02-29 Later date: 2011-02-28 Age: 11Birth date: 2000-02-29 Later date: 2011-03-01 Age: 11Birth date: 2000-03-01 Later date: 2011-02-27 Age: 10Birth date: 2000-03-01 Later date: 2011-02-28 Age: 10Birth date: 2000-03-01 Later date: 2011-03-01 Age: 11}
对于以后的日期2012-02-28:
{Birth date: 2000-02-28 Later date: 2012-02-28 Age: 12Birth date: 2000-02-28 Later date: 2012-02-29 Age: 12Birth date: 2000-02-28 Later date: 2012-03-01 Age: 12Birth date: 2000-02-29 Later date: 2012-02-28 Age: 11Birth date: 2000-02-29 Later date: 2012-02-29 Age: 12Birth date: 2000-02-29 Later date: 2012-03-01 Age: 12Birth date: 2000-03-01 Later date: 2012-02-28 Age: 11Birth date: 2000-03-01 Later date: 2012-02-29 Age: 11Birth date: 2000-03-01 Later date: 2012-03-01 Age: 12}
DateTime birth = DateTime.Parse("1.1.2000");DateTime today = DateTime.Today; //we usually don't care about birth timeTimeSpan age = today - birth; //.NET FCL should guarantee this as precisedouble ageInDays = age.TotalDays; //total number of days ... also precisedouble daysInYear = 365.2425; //statistical value for 400 yearsdouble ageInYears = ageInDays / daysInYear; //can be shifted ... not so precise
2的解是在确定总年龄方面不是那么精确,但被人们认为是精确的。人们在“手动”计算年龄时也通常使用它:
DateTime birth = DateTime.Parse("1.1.2000");DateTime today = DateTime.Today;int age = today.Year - birth.Year; //people perceive their age in years
if (today.Month < birth.Month ||((today.Month == birth.Month) && (today.Day < birth.Day))){age--; //birthday in current year not yet reached, we are 1 year younger ;)//+ no birthday for 29.2. guys ... sorry, just wrong date for birth}
注2:
这是我最喜欢的解决方案
我们不能使用DateTime. DayOfyear或TimeSpans,因为它们在闰年中转换天数
为了易读性我多放了几行
我将为它创建2个静态重载方法,一个用于通用使用,第二个用于使用友好性:
public static int GetAge(DateTime bithDay, DateTime today){//chosen solution method body}
public static int GetAge(DateTime birthDay){return GetAge(birthDay, DateTime.Now);}
// ----------------------------------------------------------------------public void CalculateAgeSamples(){PrintAge( new DateTime( 2000, 02, 29 ), new DateTime( 2009, 02, 28 ) );// > Birthdate=29.02.2000, Age at 28.02.2009 is 8 yearsPrintAge( new DateTime( 2000, 02, 29 ), new DateTime( 2012, 02, 28 ) );// > Birthdate=29.02.2000, Age at 28.02.2012 is 11 years} // CalculateAgeSamples
// ----------------------------------------------------------------------public void PrintAge( DateTime birthDate, DateTime moment ){Console.WriteLine( "Birthdate={0:d}, Age at {1:d} is {2} years", birthDate, moment, YearDiff( birthDate, moment ) );} // PrintAge
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;}}
public static Dictionary<string,int> CurrentAgeInYearsMonthsDays(DateTime? ndtBirthDate, DateTime? ndtReferralDate){//----------------------------------------------------------------------// Can't determine age if we don't have a dates.//----------------------------------------------------------------------if (ndtBirthDate == null) return null;if (ndtReferralDate == null) return null;
DateTime dtBirthDate = Convert.ToDateTime(ndtBirthDate);DateTime dtReferralDate = Convert.ToDateTime(ndtReferralDate);
//----------------------------------------------------------------------// Create our Variables//----------------------------------------------------------------------Dictionary<string, int> dYMD = new Dictionary<string,int>();int iNowDate, iBirthDate, iYears, iMonths, iDays;string sDif = "";
//----------------------------------------------------------------------// Store off current date/time and DOB into local variables//----------------------------------------------------------------------iNowDate = int.Parse(dtReferralDate.ToString("yyyyMMdd"));iBirthDate = int.Parse(dtBirthDate.ToString("yyyyMMdd"));
//----------------------------------------------------------------------// Calculate Years//----------------------------------------------------------------------sDif = (iNowDate - iBirthDate).ToString();iYears = int.Parse(sDif.Substring(0, sDif.Length - 4));
//----------------------------------------------------------------------// Store Years in Return Value//----------------------------------------------------------------------dYMD.Add("Years", iYears);
//----------------------------------------------------------------------// Calculate Months//----------------------------------------------------------------------if (dtBirthDate.Month > dtReferralDate.Month)iMonths = 12 - dtBirthDate.Month + dtReferralDate.Month - 1;elseiMonths = dtBirthDate.Month - dtReferralDate.Month;
//----------------------------------------------------------------------// Store Months in Return Value//----------------------------------------------------------------------dYMD.Add("Months", iMonths);
//----------------------------------------------------------------------// Calculate Remaining Days//----------------------------------------------------------------------if (dtBirthDate.Day > dtReferralDate.Day)//Logic: Figure out the days in month previous to the current month, or the admitted month.// Subtract the birthday from the total days which will give us how many days the person has lived since their birthdate day the previous month.// then take the referral date and simply add the number of days the person has lived this month.
//If referral date is january, we need to go back to the following year's December to get the days in that month.if (dtReferralDate.Month == 1)iDays = DateTime.DaysInMonth(dtReferralDate.Year - 1, 12) - dtBirthDate.Day + dtReferralDate.Day;elseiDays = DateTime.DaysInMonth(dtReferralDate.Year, dtReferralDate.Month - 1) - dtBirthDate.Day + dtReferralDate.Day;elseiDays = dtReferralDate.Day - dtBirthDate.Day;
//----------------------------------------------------------------------// Store Days in Return Value//----------------------------------------------------------------------dYMD.Add("Days", iDays);
return dYMD;}
Public Shared Function CalculateAge(BirthDate As DateTime) As IntegerDim HebCal As New System.Globalization.HebrewCalendar ()Dim now = DateTime.Now()Dim iAge = HebCal.GetYear(now) - HebCal.GetYear(BirthDate)Dim iNowMonth = HebCal.GetMonth(now), iBirthMonth = HebCal.GetMonth(BirthDate)If iNowMonth < iBirthMonth Or (iNowMonth = iBirthMonth AndAlso HebCal.GetDayOfMonth(now) < HebCal.GetDayOfMonth(BirthDate)) Then iAge -= 1Return iAgeEnd Function
DateTime now = DateTime.Today;DateTime birthday = new DateTime(1991, 02, 03);//3rd feb
int age = now.Year - birthday.Year;
if (now.Month < birthday.Month || (now.Month == birthday.Month && now.Day < birthday.Day))//not had bday this year yetage--;
return age;
System.DateTime birthTime = AskTheUser(myUser); // :-)System.DateTime now = System.DateTime.Now;System.TimeSpan age = now - birthTime; // As simple as thatdouble ageInDays = age.TotalDays; // Will you convert to whatever you want yourself?
DateTime birth = new DateTime(1974, 8, 29);DateTime today = DateTime.Now;TimeSpan span = today - birth;DateTime age = DateTime.MinValue + span;
// Make adjustment due to MinValue equalling 1/1/1int years = age.Year - 1;int months = age.Month - 1;int days = age.Day - 1;
// Print out not only how many years old they are but give months and days as wellConsole.Write("{0} years, {1} months, {2} days", years, months, days);
static int GetAge(LocalDate dateOfBirth){Instant now = SystemClock.Instance.Now;
// The target time zone is important.// It should align with the *current physical location* of the person// you are talking about. When the whereabouts of that person are unknown,// then you use the time zone of the person who is *asking* for the age.// The time zone of birth is irrelevant!
DateTimeZone zone = DateTimeZoneProviders.Tzdb["America/New_York"];
LocalDate today = now.InZone(zone).Date;
Period period = Period.Between(dateOfBirth, today, PeriodUnits.Years);
return (int) period.Years;}
用法:
LocalDate dateOfBirth = new LocalDate(1976, 8, 27);int age = GetAge(dateOfBirth);
public void GetAge(DateTime dob, DateTime now, out int years, out int months, out int days){years = 0;months = 0;days = 0;
DateTime tmpdob = new DateTime(dob.Year, dob.Month, 1);DateTime tmpnow = new DateTime(now.Year, now.Month, 1);
while (tmpdob.AddYears(years).AddMonths(months) < tmpnow){months++;if (months > 12){years++;months = months - 12;}}
if (now.Day >= dob.Day)days = days + now.Day - dob.Day;else{months--;if (months < 0){years--;months = months + 12;}days += DateTime.DaysInMonth(now.AddMonths(-1).Year, now.AddMonths(-1).Month) + now.Day - dob.Day;}
if (DateTime.IsLeapYear(dob.Year) && dob.Month == 2 && dob.Day == 29 && now >= new DateTime(now.Year, 3, 1))days++;
}
private string ValidateDate(DateTime dob) //This method will validate the date{int Years = 0; int Months = 0; int Days = 0;
GetAge(dob, DateTime.Now, out Years, out Months, out Days);
if (Years < 18)message = Years + " is too young. Please try again on your 18th birthday.";else if (Years >= 65)message = Years + " is too old. Date of Birth must not be 65 or older.";elsereturn null; //Denotes validation passed}
DateTime dob = DateTime.Parse("03/10/1982");
string message = ValidateDate(dob);
lbldatemessage.Visible = !StringIsNullOrWhitespace(message);lbldatemessage.Text = message ?? ""; //Ternary if message is null then default to empty string
public int GetAge(DateTime birthDate){int age = DateTime.Now.Year - birthDate.Year;
if (birthDate.DayOfYear > DateTime.Now.DayOfYear)age--;
return age;}
public static int GetAgeByLoop(DateTime birthday){var age = -1;
for (var date = birthday; date < DateTime.Today; date = date.AddYears(1)){age++;}
return age;}
DateTime today = DateTime.Today;DateTime bday = DateTime.Parse("2016-2-14");int age = today.Year - bday.Year;var unit = "";
if (bday > today.AddYears(-age)){age--;}if (age == 0) // Under one year old{age = today.Month - bday.Month;
age = age <= 0 ? (12 + age) : age; // The next year before birthday
age = today.Day - bday.Day >= 0 ? age : --age; // Before the birthday.day
unit = "month";}else {unit = "year";}
if (age > 1){unit = unit + "s";}
int AgeNow(DateTime birthday){return AgeAt(DateTime.Now, birthday);}
int AgeAt(DateTime now, DateTime birthday){return AgeAt(now, birthday, CultureInfo.CurrentCulture.Calendar);}
int AgeAt(DateTime now, DateTime birthday, Calendar calendar){// My age has increased on the morning of my// birthday even though I was born in the evening.now = now.Date;birthday = birthday.Date;
var age = 0;if (now <= birthday) return age; // I am zero now if I am to be born tomorrow.
while (calendar.AddYears(birthday, age + 1) <= now){age++;}return age;}
PASSED: someone born on 28 February 1964 is age 4 on 28 February 1968PASSED: someone born on 29 February 1964 is age 3 on 28 February 1968PASSED: someone born on 31 December 2016 is age 0 on 01 January 2017
C#// get the difference in yearsint years = DateTime.Now.Year - BirthDate.Year;// subtract another year if we're before the// birth day in the current yearif (DateTime.Now.Month < BirthDate.Month ||(DateTime.Now.Month == BirthDate.Month &&DateTime.Now.Day < BirthDate.Day))years--;VB.NET' get the difference in yearsDim years As Integer = DateTime.Now.Year - BirthDate.Year' subtract another year if we're before the' birth day in the current yearIf DateTime.Now.Month < BirthDate.Month Or (DateTime.Now.Month = BirthDate.Month And DateTime.Now.Day < BirthDate.Day) Thenyears = years - 1End If
public static int AgeInYears(this System.DateTime source, System.DateTime target)=> target.Year - source.Year is int age && age > 0 && source.AddYears(age) > target ? age - 1 : age < 0 && source.AddYears(age) < target ? age + 1 : age;
如果时间的方向是“负的”,年龄也将是负的。
可以添加一个分数,表示从目标到下一个生日累积的年龄量:
public static double AgeInTotalYears(this System.DateTime source, System.DateTime target){var sign = (source <= target ? 1 : -1);
var ageInYears = AgeInYears(source, target); // The method above.
var last = source.AddYears(ageInYears);var next = source.AddYears(ageInYears + sign);
var fractionalAge = (double)(target - last).Ticks / (double)(next - last).Ticks * sign;
return ageInYears + fractionalAge;}