0

我正在尝试计算事件提供者的开始时间。

我有 3 个变量:

DateTime eventStartTime
DateTime currentTime
TimeSpan timeBetweenEvents

eventStartTime是任何给定日期的所需开始时间,例如“6:00AM” 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;
}
4

1 回答 1

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));
}
于 2013-03-28T23:52:57.247 回答