我正在尝试计算事件提供者的开始时间。
我有3个变量:
DateTime eventStartTime
DateTime currentTime
TimeSpan timeBetweenEvents
eventStartTime
是任何一天所需的开始时间,例如“上午6:00”
currentTime
是当前时间
timeBetweenEvents
是事件执行之间的TimeSpan
这是我的代码:
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 :(得分:2)
使用简单的while循环通过递增eventStartTime来解决此问题,直到它在当前时间之后。这很容易受到一些数据问题的影响,但可以满足我的需要。
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));
}