我目前正在开展一项我满足要求的学校项目,但我想挑战自己。如何根据今天的日期/时间以下列格式准确显示我的年龄?
年龄:27岁 - 或 - 天 - 或 - 小时 - 或 - 秒(闰年会计)
研究我做了:How would you calculate the age in C# using date of birth (considering leap years)
我更喜欢它背后的数学。这是我目前正在使用的数学,但它只能精确到16小时或960分钟或57,600秒。
// Tried using "double" datatype, still same problem.
int years = DateTime.Now.Year - dateBirthDate.Year;
int days = (years / 4) + (years * 365);
int hours = (days * 24) + DateTime.Now.Hour;
int minutes = hours * 60;
int seconds = (minutes * 60) + ((DateTime.Now.Hour * 60) * 60) + DateTime.Now.Second;
应显示接近0。
输出:
Thank you Mat, what is your date of birth? Feel free to include the time you were born. 09/08/2018 5:11pm
Years :0
Days :0
Minutes :1020
Seconds :122425
我已经设法使代码部分工作,但发现了另一个不可预见的问题。现在它不会解释尚未到来的生日。思考?
//Needed casting so I could remove the decimals.
TimeSpan span = DateTime.Now.Subtract(dateBirthDate);
int years = (int)span.Days/365;
int months = years * 12;
int days = (int)span.TotalDays;
int hours = (int)span.TotalHours;
int minutes = (int)span.TotalMinutes;
int seconds = (int)span.TotalSeconds;
不得不将TimeSpan强制转换为int来删除小数。为了抓住TimeSpan年份,我只花了几个月并除以365,然后将其转换为(int),这样它只显示整数。然后我创建了一个if / else条件和一个嵌套的条件来调整当前正在发生或尚未到来的生日。逻辑看似合理。
//Needed casting so I could remove the decimals.
TimeSpan span = DateTime.Now.Subtract(dateBirthDate);
//Creating workable if/else to account for birthday's yet to come.
int dateCorrectorMonthNow = DateTime.Now.Month;
int dateCorrectorDayNow = DateTime.Now.Day;
int dateCorrectorMonthThen = dateBirthDate.Month;
int dateCorrectorDayThen = dateBirthDate.Day;
int years = (int)span.Days/365;
int months = years * 12;
int days = (int)span.TotalDays;
int hours = (int)span.TotalHours;
int minutes = (int)span.TotalMinutes;
int seconds = (int)span.TotalSeconds;
if (dateCorrectorMonthNow <= dateCorrectorMonthThen)
{
if (dateCorrectorDayNow <= dateCorrectorDayThen)
{
Console.WriteLine($"Years :{years}");
}
else
{
Console.WriteLine($"Years :{years-1}");
}
}
else
{
Console.WriteLine($"Years :{years}");
}