2013-02-26 88 views
1

我有以下日期時間:分裂週期分爲月部分

Start = 15/12/2012 13:00:00 
End = 16/02/2013 14:00:00 

我怎麼能分裂,在3份每月?

- 15-12-2012 13:00:00 -> 01-01-2013 00:00:00 
- 01-01-2013 00:00:00 -> 01-02-2013 00:00:00 
- 01-02-2013 00:00:00 -> 16-02-2013 14:00:00 

總時間段必須保持不變。 使用LINQ可以輕鬆完成嗎?

+0

什麼是用例?你需要做什麼? – Oded 2013-02-26 10:03:50

+0

你是什麼意思,分成三部分,以相同的時間跨度? Timespan似乎不一樣! – 2013-02-26 10:04:54

回答

6

肯定,嘗試(包含小的輔助類)這

過程:

var Start = DateTime.Parse("15 Dec 2012 13:00:00"); 
var End = DateTime.Parse("16 Feb 2013 14:00:00"); 

var runningDate = Start; 
while (runningDate < End) 
{ 
    var nextMonthSeed = runningDate.AddMonths(1); 
    var to = DateHelper.Min(new DateTime(nextMonthSeed.Year, nextMonthSeed.Month, 1), End); 
    Console.WriteLine("{0} -> {1}", runningDate.ToString("dd-MM-yyyy HH:mm:ss"), to.ToString("dd-MM-yyyy HH:mm:ss")); 
    runningDate = to; 
} 

幫助程序類別:

public static class DateHelper 
{ 
    public static DateTime Min(DateTime date1, DateTime date2) 
    { 
     return (date1 < date2 ? date1 : date2); 
    } 
} 
1

你可以嘗試一些像這樣的擴展方法:

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); 

    } 
} 

和產生這些結果(在一個控制檯應用程序):

enter image description here

編輯完