给定代表某人生日的DateTime,我如何计算他们的年龄(以年为单位)?
当前回答
这是最准确的答案之一,它能够解决2月29日的生日,而不是2月28日的任何一年。
public int GetAge(DateTime birthDate)
{
int age = DateTime.Now.Year - birthDate.Year;
if (birthDate.DayOfYear > DateTime.Now.DayOfYear)
age--;
return age;
}
其他回答
这是一个非常适合我的功能。没有计算,非常简单。
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));
}
我认为这个问题可以用这样一种更简单的方法解决-
该类可以是-
using System;
namespace TSA
{
class BirthDay
{
double ageDay;
public BirthDay(int day, int month, int year)
{
DateTime birthDate = new DateTime(year, month, day);
ageDay = (birthDate - DateTime.Now).TotalDays; //DateTime.UtcNow
}
internal int GetAgeYear()
{
return (int)Math.Truncate(ageDay / 365);
}
internal int GetAgeMonth()
{
return (int)Math.Truncate((ageDay % 365) / 30);
}
}
}
电话可以是这样的-
BirthDay b = new BirthDay(1,12,1990);
int year = b.GetAgeYear();
int month = b.GetAgeMonth();
private int GetYearDiff(DateTime start, DateTime end)
{
int diff = end.Year - start.Year;
if (end.DayOfYear < start.DayOfYear) { diff -= 1; }
return diff;
}
[Fact]
public void GetYearDiff_WhenCalls_ShouldReturnCorrectYearDiff()
{
//arrange
var now = DateTime.Now;
//act
//assert
Assert.Equal(24, GetYearDiff(new DateTime(1992, 7, 9), now)); // passed
Assert.Equal(24, GetYearDiff(new DateTime(1992, now.Month, now.Day), now)); // passed
Assert.Equal(23, GetYearDiff(new DateTime(1992, 12, 9), now)); // passed
}
我有一个定制的计算年龄的方法,加上一条奖金验证消息,以防有帮助:
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.";
else
return null; //Denotes validation passed
}
方法调用此处并传递日期时间值(如果服务器设置为美国语言环境,则为MM/dd/yyyy)。将其替换为消息框或要显示的任何容器:
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
记住,您可以按任何方式格式化邮件。
var EndDate = new DateTime(2022, 4, 21);
var StartDate = new DateTime(1986, 4, 25);
Int32 Months = EndDate.Month - StartDate.Month;
Int32 Years = EndDate.Year - StartDate.Year;
Int32 Days = EndDate.Day - StartDate.Day;
if (Days < 0)
{
Months = Months - 1;
}
if (Months < 0)
{
Years = Years - 1;
Months = Months + 12;
}
string Ages = Years.ToString() + " Year(s) " + Months.ToString() + " Month(s) ";
推荐文章
- HTTP POST返回错误:417“期望失败。”
- 如何在。net中创建和使用资源
- 为什么Path。以Path.DirectorySeparatorChar开头的文件名合并不正确?
- 如何在c#中获得正确的时间戳
- Linq选择列表中存在的对象(A,B,C)
- c# .NET中的App.config是什么?如何使用它?
- c#:如何获得一个字符串的第一个字符?
- String类中的什么方法只返回前N个字符?
- 如何在PowerShell格式化日期时间
- 我如何提高ASP。NET MVC应用程序性能?
- 更好的方法将对象转换为int类型
- 我可以将c#字符串值转换为转义字符串文字吗?
- 在c#中转换char到int
- c#中朋友的对等物是什么?
- 关键字使用virtual+override vs. new