你可以嘗試一些像這樣的擴展方法:
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);
}
}
和產生這些結果(在一個控制檯應用程序):
編輯完
什麼是用例?你需要做什麼? – Oded 2013-02-26 10:03:50
你是什麼意思,分成三部分,以相同的時間跨度? Timespan似乎不一樣! – 2013-02-26 10:04:54