【发布时间】:2012-05-23 23:54:24
【问题描述】:
这是一个问题。我见过很多解决方案,但似乎没有一个符合我想要的标准......
我想用这种格式显示年龄
20 y(s) 2 m(s) 20 d(s)
20 y(s) 2 m(s)
2 m(s) 20 d(s)
20 d(s)
等等……
我尝试了几种解决方案,但闰年导致了我的问题。由于闰年,我的单元测试总是失败,无论间隔多少天,闰年都会计算额外的天数。
这是我的代码....
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);
【问题讨论】:
-
这个问题被问了太多次了,你没有发现任何有用的?
-
@V4Vendetta 不幸的是,从来没有这样问过。我的意思是,问题是别的,让我更新我的描述......
-
@NaveedButt,你的问题有何不同?
-
@jrummell 看到 HackedByChinese 的评论,他已经说得很清楚了,他和其他人的答案的区别......我的用户需要精确的年龄
标签: c# asp.net .net c#-4.0 datetime