您可以尝试以下扩展方法:
public static class SomeExtensions {
public static IEnumerable<Tuple<DateTime, DateTime>> GetIntervals(
this DateTime from,
DateTime to) {
var currentFrom = from;
var currentTo = from.AdvanceToStartOfNextMonth();
while (currentTo < to) {
yield return Tuple.Create(currentFrom, currentTo);
currentFrom = currentTo;
currentTo = currentFrom.AdvanceToStartOfNextMonth();
}
yield return Tuple.Create(currentFrom, to);
}
public static DateTime AdvanceToStartOfNextMonth(this DateTime @this) {
var newMonth = @this.Month + 1;
var newYear = @this.Year;
if (newMonth == 13) {
newMonth = 1;
newYear++;
}
return new DateTime(newYear, newMonth, 1);
}
}
然后像这样使用它们:
public class Etc {
public static void Foo() {
DateTime start = ...
DateTime stop = ....
Tuple<DateTime, DateTime>[] intervals = start.GetIntervals(stop).ToArray();
// or simply
foreach (var interval in start.GetIntervals(stop))
Console.WriteLine(interval);
}
}
编辑
这是我刚刚尝试过的一个小测试(我认为它看起来不错):
class Program {
static void Main(string[] args) {
DateTime start = DateTime.Now.Subtract(TimeSpan.FromDays(170));
DateTime stop = DateTime.Now;
foreach (var interval in start.GetIntervals(stop))
Console.WriteLine(interval);
Console.ReadKey(intercept: true);
}
}
并产生了这些结果(在控制台应用程序中):

编辑结束