Ric*_*III 110
我已经编写了一个适用于相隔一年的日期的实现.
但是,与其他算法不同,它不能优雅地处理负时间跨度.它也不使用自己的日期算术,而是依赖于标准库.
所以不用多说,这里是代码:
DateTime zeroTime = new DateTime(1, 1, 1);
DateTime a = new DateTime(2007, 1, 1);
DateTime b = new DateTime(2008, 1, 1);
TimeSpan span = b - a;
// Because we start at year 1 for the Gregorian
// calendar, we must subtract a year here.
int years = (zeroTime + span).Year - 1;
// 1, where my other algorithm resulted in 0.
Console.WriteLine("Yrs elapsed: " + years);
Run Code Online (Sandbox Code Playgroud)
dan*_*ana 44
使用:
int Years(DateTime start, DateTime end)
{
return (end.Year - start.Year - 1) +
(((end.Month > start.Month) ||
((end.Month == start.Month) && (end.Day >= start.Day))) ? 1 : 0);
}
Run Code Online (Sandbox Code Playgroud)
小智 23
我们必须编码检查以确定两个日期之间的差异,即开始日期和结束日期是否大于2年.
感谢上面的提示,它完成如下:
DateTime StartDate = Convert.ToDateTime("01/01/2012");
DateTime EndDate = Convert.ToDateTime("01/01/2014");
DateTime TwoYears = StartDate.AddYears(2);
if EndDate > TwoYears .....
Run Code Online (Sandbox Code Playgroud)
dav*_*avo 14
如果你因为琐碎的原因需要了解某人的年龄,那么Timespan就可以,但如果你需要计算退休金,长期存款或其他任何用于财务,科学或法律目的的话,那么我恐怕Timespan不够准确,因为Timespan假设每年都有相同的天数,相同的小时数和相同的秒数.
实际上,某些年份的长度会有所不同(出于不同的原因,超出了本答案的范围).为了解决Timespan的限制,你可以模仿Excel的作用:
public int GetDifferenceInYears(DateTime startDate, DateTime endDate)
{
//Excel documentation says "COMPLETE calendar years in between dates"
int years = endDate.Year - startDate.Year;
if (startDate.Month == endDate.Month &&// if the start month and the end month are the same
endDate.Day < startDate.Day// AND the end day is less than the start day
|| endDate.Month < startDate.Month)// OR if the end month is less than the start month
{
years--;
}
return years;
}
Run Code Online (Sandbox Code Playgroud)
var totalYears =
(DateTime.Today - new DateTime(2007, 03, 11)).TotalDays
/ 365.2425;
Run Code Online (Sandbox Code Playgroud)
int Age = new DateTime((DateTime.Now - BirthDateTime).Ticks).Year;
Run Code Online (Sandbox Code Playgroud)
要计算经过的年数(年龄),结果将为减一。
var timeSpan = DateTime.Now - birthDateTime;
int age = new DateTime(timeSpan.Ticks).Year - 1;
Run Code Online (Sandbox Code Playgroud)
小智 6
这是一个巧妙的技巧,可以让系统自动处理闰年。它为所有日期组合提供了准确的答案。
DateTime dt1 = new DateTime(1987, 9, 23, 13, 12, 12, 0);
DateTime dt2 = new DateTime(2007, 6, 15, 16, 25, 46, 0);
DateTime tmp = dt1;
int years = -1;
while (tmp < dt2)
{
years++;
tmp = tmp.AddYears(1);
}
Console.WriteLine("{0}", years);
Run Code Online (Sandbox Code Playgroud)
目前还不清楚你想如何处理小数年,但也许像这样:
DateTime now = DateTime.Now;
DateTime origin = new DateTime(2007, 11, 3);
int calendar_years = now.Year - origin.Year;
int whole_years = calendar_years - ((now.AddYears(-calendar_years) >= origin)? 0: 1);
int another_method = calendar_years - ((now.Month - origin.Month) * 32 >= origin.Day - now.Day)? 0: 1);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
134402 次 |
| 最近记录: |