2013-03-28 42 views
0

我正在計算事件提供者的開始時間。如何計算我的活動提供者的下一次運行時間?

我有3個變量:

DateTime eventStartTime 
DateTime currentTime 
TimeSpan timeBetweenEvents 

eventStartTime是在例如任何一天所希望的開始時間「6:00 AM」 currentTime是當前時間 timeBetweenEvents的事件執行之間的時間跨度

這是我的代碼:

public static TimeSpan GetTimeToStart(DateTime eventStartTime, DateTime currentTime, TimeSpan timeBetweenEvents) 
{ 
    TimeSpan timeToStart; 
    // e.g. if it is before 6:00AM today 
    if(DateTime.Now < merchantEventStartTime) 
     timeToStart = merchantEventStartTime - DateTime.Now; 
    // otherwise process at timeToStart + ISO8601 specified merchantEventProviderSchedule 
    else 
     timeToStart = merchantEventStartTime - DateTime.Now + merchantEventProviderSchedule; 
    return timeToStart; 
} 
+0

任何理由downvotes? – Codeman

+0

也有興趣爲什麼OP被downvoted兩次 – Kcvin

回答

2

使用一個簡單的循環,同時解決了這個通過增加eventStartTime直到AFTER當前時間。這對於一些數據問題很脆弱,但適用於我需要的功能。

public static TimeSpan GetTimeToStart(DateTime eventStartTime, DateTime currentTime, TimeSpan timeBetweenEvents) 
{ 
    while(eventStartTime < currentTime) 
     eventStartTime = eventStartTime.Add(timeBetweenEvents); 

    return eventStartTime - currentTime; 
} 

單元測試驗證我的結果:

public void TestGetTimeToStart() 
{ 
    //5AM currentTime 
    DateTime now = DateTime.Now; 
    var timeToStartBefore6am = AlertingService.GetTimeToStart(
     new DateTime(now.Year, now.Month, now.Day, 6, 0, 0), 
     new DateTime(now.Year, now.Month, now.Day, 5, 0, 0), 
     XmlConvert.ToTimeSpan("PT12H")); 
    Assert.IsNotNull(timeToStartBefore6am); 
    Assert.AreEqual(timeToStartBefore6am, new TimeSpan(1, 0, 0)); 

    //5PM currentTime 
    var timeToStartBefore6pm = AlertingService.GetTimeToStart(
     new DateTime(now.Year, now.Month, now.Day, 6, 0, 0), 
     new DateTime(now.Year, now.Month, now.Day, 17, 0, 0), 
     XmlConvert.ToTimeSpan("PT12H")); 
    Assert.IsNotNull(timeToStartBefore6pm); 
    Assert.AreEqual(timeToStartBefore6pm, new TimeSpan(1, 0, 0)); 

    //7PM currentTime 
    var timeToStartAfter6pm = AlertingService.GetTimeToStart(
     new DateTime(now.Year, now.Month, now.Day, 6, 0, 0), 
     new DateTime(now.Year, now.Month, now.Day, 19, 0, 0), 
     XmlConvert.ToTimeSpan("PT12H")); 
    Assert.IsNotNull(timeToStartAfter6pm); 
    Assert.AreEqual(timeToStartAfter6pm, new TimeSpan(11, 0, 0)); 
}