public DateTime GetNextDateTime(DateTime fromMoment) { Time fromMomentTime = fromMoment.GetTime(); short fromTime = fromMomentTime.ToShort(); // Check if we have to apply the initial run if (_startingTime.ToShort() >= fromTime || _endingTime.ToShort() <= fromTime) { return(fromMoment.ForwardToTime(_startingTime)); } // Calculate what the closest interval point is // First calculate the difference in minutes int diffMinutes = (fromMomentTime.Hour - _startingTime.Hour) * Time.MaxMinute + fromMomentTime.Minute - _startingTime.Minute; // Calculate how many times the timeout has passed in this difference float timeoutTimes = (float)diffMinutes / GetMinuteTimeout(); // Check if this is approximately a round number // Because then we have to undertake action now! if (timeoutTimes % 1 < double.Epsilon) { return(fromMoment); } DateTime nextDateTime = fromMoment.AddMinutesRound((int)(Math.Ceiling(timeoutTimes) * GetMinuteTimeout())); // Make sure the time does not exceed the end time if (nextDateTime.GetTime() > _endingTime) { return(fromMoment.ForwardToTime(_startingTime)); } return(nextDateTime); }