C#计算准确的年龄

任何人都知道如何根据日期(出生日期)获得年龄

我想到这样的事情

string age = DateTime.Now.GetAccurateAge(); 

输出将是20年5月20日的一些事情

 public static class DateTimeExtensions { public static string ToAgeString(this DateTime dob) { DateTime today = DateTime.Today; int months = today.Month - dob.Month; int years = today.Year - dob.Year; if (today.Day < dob.Day) { months--; } if (months < 0) { years--; months += 12; } int days = (today - dob.AddMonths((years * 12) + months)).Days; return string.Format("{0} year{1}, {2} month{3} and {4} day{5}", years, (years == 1) ? "" : "s", months, (months == 1) ? "" : "s", days, (days == 1) ? "" : "s"); } } 

请参阅如何计算C#中某人的年龄? 为了想法。

不确定它是否总是正确的(没有想过是否有一些闰年等情况可能导致它失败……),但这是一个简单的方法来摆脱年月:

 DateTime bd = DateTime.Parse("2009-06-17"); TimeSpan ts = DateTime.Now.Subtract(bd); DateTime age = DateTime.MinValue + ts; string s = string.Format("{0} Years {1} months {2} days", age.Year -1 , age.Month - 1, age.Day - 1); 

见http://techbrij.com/210/convert-timespan-to-year-month-date-age-calculation-in-net

这听起来像是一个很好的练习,可以更好地了解TimeSpan课程 。

由于我不能将代码发布到评论中,这里是基于@LukeH答案的代码,修复了错误

 public static int GetAge( DateTime dob, DateTime today, out int days, out int months ) { DateTime dt = today; if( dt.Day < dob.Day ) { dt = dt.AddMonths( -1 ); } months = dt.Month - dob.Month; if( months < 0 ) { dt = dt.AddYears( -1 ); months += 12; } int years = dt.Year - dob.Year; var offs = dob.AddMonths( years * 12 + months ); days = (int)( ( today.Ticks - offs.Ticks ) / TimeSpan.TicksPerDay ); return years; } 

为了获得年龄,我将使用生日的日期时间,并找出它与当前系统时间之间的差异。 此链接显示如何查找两个日期时间之间的差异。 只需将starttime设置为用户的生日和结束时间(DateTime.Now;)

这是我使用的:

  public static int GetAge(DateTime dateOfBirth) { int age = DateTime.Now.Year - dateOfBirth.Year; if (dateOfBirth.AddYears(age) > DateTime.Now) { age = age - 1; } return age; } 

试试这个。 它在两个日期之间的所有日子循环,并在途中计算天,月和年。 这就是我需要的。

  public static class DateTimeExtension { ///  /// Returns day, month, and year by subtracting date2 from date1 ///  /// the date from which date2 will be subtracted /// this date will be subtracted from date1 ///  public static string GetAge(this DateTime date1, DateTime date2) { int y = 0, m = 0, d = 0; for (DateTime i = date2; i < date1; i = i.AddDays(1)) { d++; if (d >= DateTime.DaysInMonth(i.Year, i.Month)) { d = 0; m++; } if (m >= 12) { y++; m = 0; } } return "Time-span: " + y + " Year(s), " + m + " Month(s), " + d + " Day(s)"; } } 

使用方法:

  Console.WriteLine(new DateTime(2018, 4, 24).GetAge(new DateTime(2018,1,3))); //Time-span: 0 Year(s), 3 Month(s), 20 Day(s) Console.WriteLine(new DateTime(2010, 4, 24).GetAge(new DateTime(2000, 7, 23))); //Time-span: 9 Year(s), 9 Month(s), 2 Day(s)