给定代表某人生日的DateTime,我如何计算他们的年龄(以年为单位)?
当前回答
public string GetAge(this DateTime birthdate, string ageStrinFormat = null)
{
var date = DateTime.Now.AddMonths(-birthdate.Month).AddDays(-birthdate.Day);
return string.Format(ageStrinFormat ?? "{0}/{1}/{2}",
(date.Year - birthdate.Year), date.Month, date.Day);
}
其他回答
无分支解决方案:
public int GetAge(DateOnly birthDate, DateOnly today)
{
return today.Year - birthDate.Year + (((today.Month << 5) + today.Day - ((birthDate.Month << 5) + birthDate.Day)) >> 31);
}
我创建了一个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 static string ToAge(this DateTime dob, DateTime? toDate = null)
{
if (!toDate.HasValue)
toDate = DateTime.Now;
var now = toDate.Value;
if (now.CompareTo(dob) < 0)
return "Future date";
int years = now.Year - dob.Year;
int months = now.Month - dob.Month;
int days = now.Day - dob.Day;
if (days < 0)
{
months--;
days = DateTime.DaysInMonth(dob.Year, dob.Month) - dob.Day + now.Day;
}
if (months < 0)
{
years--;
months = 12 + months;
}
return string.Format("{0} year(s), {1} month(s), {2} days(s)",
years,
months,
days);
}
这里是一个单元测试:
[Test]
public void ToAgeTests()
{
var date = new DateTime(2000, 1, 1);
Assert.AreEqual("0 year(s), 0 month(s), 1 days(s)", new DateTime(1999, 12, 31).ToAge(date));
Assert.AreEqual("0 year(s), 0 month(s), 0 days(s)", new DateTime(2000, 1, 1).ToAge(date));
Assert.AreEqual("1 year(s), 0 month(s), 0 days(s)", new DateTime(1999, 1, 1).ToAge(date));
Assert.AreEqual("0 year(s), 11 month(s), 0 days(s)", new DateTime(1999, 2, 1).ToAge(date));
Assert.AreEqual("0 year(s), 10 month(s), 25 days(s)", new DateTime(1999, 2, 4).ToAge(date));
Assert.AreEqual("0 year(s), 10 month(s), 1 days(s)", new DateTime(1999, 2, 28).ToAge(date));
date = new DateTime(2000, 2, 15);
Assert.AreEqual("0 year(s), 0 month(s), 28 days(s)", new DateTime(2000, 1, 18).ToAge(date));
}
这个解决方案怎么样?
static string CalcAge(DateTime birthDay)
{
DateTime currentDate = DateTime.Now;
int approximateAge = currentDate.Year - birthDay.Year;
int daysToNextBirthDay = (birthDay.Month * 30 + birthDay.Day) -
(currentDate.Month * 30 + currentDate.Day) ;
if (approximateAge == 0 || approximateAge == 1)
{
int month = Math.Abs(daysToNextBirthDay / 30);
int days = Math.Abs(daysToNextBirthDay % 30);
if (month == 0)
return "Your age is: " + daysToNextBirthDay + " days";
return "Your age is: " + month + " months and " + days + " days"; ;
}
if (daysToNextBirthDay > 0)
return "Your age is: " + --approximateAge + " Years";
return "Your age is: " + approximateAge + " Years"; ;
}
我对Mark Soen的答案做了一个小小的修改:我重写了第三行,以便可以更容易地解析表达式。
public int AgeInYears(DateTime bday)
{
DateTime now = DateTime.Today;
int age = now.Year - bday.Year;
if (bday.AddYears(age) > now)
age--;
return age;
}
为了清晰起见,我还将其转换为函数。
推荐文章
- 将字符串转换为System.IO.Stream
- MySQL中两个日期之间的差异
- 如何从枚举中选择一个随机值?
- 驻留在App_Code中的类不可访问
- 在链式LINQ扩展方法调用中等价于'let'关键字的代码
- dynamic (c# 4)和var之间的区别是什么?
- Visual Studio: ContextSwitchDeadlock
- Sql Server字符串到日期的转换
- 返回文件在ASP。Net Core Web API
- 自定义HttpClient请求头
- 如果我使用OWIN Startup.cs类并将所有配置移动到那里,我是否需要一个Global.asax.cs文件?
- VS2013外部构建错误"error MSB4019: The imported project <path> was not found"
- 从另一个列表id中排序一个列表
- 等待一个无效的异步方法
- 无法加载文件或程序集…参数不正确