所以我有所有这些旅行日期,从日期到现在。我想把所有的旅行天数加起来,然后按年份排序。但是,如果一次旅行跨越两年,我的代码将达到错误的总和:-(
给定
From date To date Number of days
01.01.2001 01.02.2001 32
01.01.2002 01.02.2002 32
01.05.2002 01.08.2002 93
20.12.2002 01.03.2003 72
01.02.2009 01.02.2010 366
01.01.2013 02.02.2015 763
Sum 1358
我的代码产生了这个。然而,它犯了一个错误:
Year Total days
2001 32
2002 137
2003 60
2009 334
2010 32
2013 365
2014 398 <---- here is a case where my code is wrong
Sum 1358
代码
var dates = new Dictionary<int, int>();
var stays = GetStays();
var returnString = "Year, Total days<br><br>";
foreach (var stay in stays)
{
var totalTravelDays = stay.ToDate.Value.AddDays(1) - stay.FromDate;
var currentYear = stay.FromDate.Value.Year;
var nextYear = stay.FromDate.Value.AddYears(1).Year;
var nextYearDate = new DateTime(stay.FromDate.Value.Year, 1, 1).AddYears(1);
var daysInThisYear = new TimeSpan?();
var daysInNextYear = new TimeSpan?();
if (stay.FromDate.Value.Year != stay.ToDate.Value.Year)
{
daysInThisYear = nextYearDate - stay.FromDate;
daysInNextYear = totalTravelDays - daysInThisYear;
}
else
{
daysInThisYear = totalTravelDays;
daysInNextYear = new TimeSpan(0);
}
if (dates.ContainsKey(currentYear))
dates[currentYear] += daysInThisYear.Value.Days;
else
dates[currentYear] = daysInThisYear.Value.Days;
if (dates.ContainsKey(nextYear))
dates[nextYear] += daysInNextYear.Value.Days;
else
dates[nextYear] = daysInNextYear.Value.Days;
}
帮助表示赞赏:)