我会尝试一下...您可以使用 Linq 一次生成所有日期范围。这不是最漂亮的查询,但它确实有效。
DateTime start = ...
DateTime end = ...
var cal = System.Globalization.CultureInfo.CurrentCulture.Calendar;
var range =
from y in Enumerable.Range(start.Year, end.Year - start.Year + 1)
let maxMonth = y < end.Year ? cal.GetMonthsInYear(y) : end.Month
let minMonth = y > start.Year ? 1 : start.Month
from m in Enumerable.Range(minMonth, maxMonth - minMonth + 1)
let isStart = (y == start.Year && m == start.Month)
let isEnd = (y == end.Year && m == end.Month)
select new
{
StartDate = isStart ? start : new DateTime(y, m, 1),
EndDate = isEnd ? end : new DateTime(y, m, cal.GetDaysInMonth(y, m)),
NumberOfMonths = isStart || isEnd ? .5 : 1
};
start
它从到多年来end
迭代,然后在每年的几个月中迭代,对边缘情况(isStart
和isEnd
)进行特殊处理。这个基本算法可以封装在这样的函数中:
public class DateTimeRange
{
Date StartDate { get; set; }
Date EndDate { get; set; }
float NumberOfMonths { get; set; }
}
public static IEnumerable<DateTimeRange> SplitByMonths(DateTime start,
DateTime end,
Calendar cal)
{
return (
from y in Enumerable.Range(start.Year, end.Year - start.Year + 1)
let maxMonth = y < end.Year ? cal.GetMonthsInYear(y) : end.Month
let minMonth = y > start.Year ? 1 : start.Month
from m in Enumerable.Range(minMonth, maxMonth - minMonth + 1)
let isStart = (y == start.Year && m == start.Month)
let isEnd = (y == end.Year && m == end.Month)
select new DateTimeRange
{
StartDate = isStart ? start : new DateTime(y, m, 1),
EndDate = isEnd ? end : new DateTime(y, m, cal.GetDaysInMonth(y, m)),
NumberOfMonths = isStart || isEnd ? .5 : 1
});
}