这是一个问题。我见过很多解决方案,但似乎没有人符合我想要的标准......
我想以这种格式显示年龄
20 y(s) 2 m(s) 20 d(s)
20 y(s) 2 m(s)
2 m(s) 20 d(s)
20 d(s)
ETC...
我已经尝试了几种解决方案,但是闰年导致了我的问题。由于闰年,我的单元测试总是失败,无论间隔多少天,闰年都会计算额外的天数。
这是我的代码....
public static string AgeDiscription(DateTime dateOfBirth)
{
var today = DateTime.Now;
var days = GetNumberofDaysUptoNow(dateOfBirth);
var months = 0;
var years = 0;
if (days > 365)
{
years = today.Year - dateOfBirth.Year;
days = days % 365;
}
if (days > DateTime.DaysInMonth(today.Year, today.Month))
{
months = Math.Abs(today.Month - dateOfBirth.Month);
for (int i = 0; i < months; i++)
{
days -= DateTime.DaysInMonth(today.Year, today.AddMonths(0 - i).Month);
}
}
var ageDescription = new StringBuilder("");
if (years != 0)
ageDescription = ageDescription.Append(years + " y(s) ");
if (months != 0)
ageDescription = ageDescription.Append(months + " m(s) ");
if (days != 0)
ageDescription = ageDescription.Append(days + " d(s) ");
return ageDescription.ToString();
}
public static int GetNumberofDaysUptoNow(DateTime dateOfBirth)
{
var today = DateTime.Now;
var timeSpan = today - dateOfBirth;
var nDays = timeSpan.Days;
return nDays;
}
有任何想法吗???
更新:
我希望两个日期之间的差异为:
var dateOfBirth = DateTime.Now.AddYears(-20);
string expected = "20 y(s) ";
string actual; // returns 20 y(s) 5 d(s)
actual = Globals.AgeDiscription(dateOfBirth);
Assert.AreEqual(expected, actual);