示例:给定一个连续的日期范围列表
列表=2001年1月1日至2001年8月14日
List1 =2001年8月15日至2002年7月10日
让我们假设一个财政年度是从7月1日到6月30日(明年的),所以产出应该是
AnotherList =2000年7月1日至2001年6月30日
期间:2001年1月1日至2001年6月30日
AnotherList1 =2001年7月1日至2002年6月30日
2001年7月1日至2001年8月14日期间:2001年8月15日至2002年6月30日
AnotherList2 =2002年7月1日至2003年6月30日
期间:2002年7月1日至2002年7月10日
同样,手工计算也很容易,但是我的方法包含了近100行代码,并结合了if each、每一个循环和while循环,我认为这是很难看的。我正在努力简化算法,以便更容易维护和调试。提前谢谢。
发布于 2010-07-20 12:55:35
你可以对GroupBy很聪明
// Beginning of earliest financial year
var start = new DateTime(2000,7,1);
var range = Enumerable.Range(0,365*2);
// Some random test data
var dates1 = range.Select(i => new DateTime(2001,1,1).AddDays(i) );
var dates2 = range.Select(i => new DateTime(2003,1,1).AddDays(i) );
// Group by distance in years from beginning of earliest financial year
var finYears =
dates1
.Concat(dates2)
.GroupBy(d => d.Subtract(start).Days / 365 );这给出了一个IEnumerable<IGrouping<int, DateTime>>,每个外部枚举都包含单个财政年度中两个列表中的所有日期。
发布于 2010-07-20 02:39:32
for each range in list
// determine end of this fiscal year
cut = new Date(range.start.year, 06, 31)
if cut < range.start
cut += year
end
if (range.end <= cut)
// one fiscal year
result.add range
continue
end
result.add new Range(range.start, cut)
// chop off whole fiscal years
start = cut + day
while (start + year <= range.end)
result.add new Range(start, start + year - day)
start += year
end
result.add new Range(start, range.end)
end对不起,红宝石和爪哇混合在一起:)
发布于 2020-01-20 09:33:33
这是我最简单的财政年度列表生成代码。
public void financialYearList()
{
List<Dictionary<string, DateTime>> diclist = new List<Dictionary<string, DateTime>>();
//financial year start from july and end june
int year = DateTime.Now.Month >= 7 ? DateTime.Now.Year + 1 : DateTime.Now.Year;
for (int i = 7; i <= 12; i++)
{
Dictionary<string, DateTime> dic = new Dictionary<string, DateTime>();
var first = new DateTime(year-1, i,1);
var last = first.AddMonths(1).AddDays(-1);
dic.Add("first", first);
dic.Add("lst", last);
diclist.Add(dic);
}
for (int i = 1; i <= 6; i++)
{
Dictionary<string, DateTime> dic = new Dictionary<string, DateTime>();
var first = new DateTime(year, i, 1);
var last = first.AddMonths(1).AddDays(-1);
dic.Add("first", first);
dic.Add("lst", last);
diclist.Add(dic);
}
}https://stackoverflow.com/questions/3286526
复制相似问题