I guess this will fit your needs. Keep in mind that it checks to the exact tick (1/10000th of a second).
static bool IsAtExactInterval(TimeSpan value, TimeSpan interval)
{
long remainder = value.Ticks % interval.Ticks;
return remainder == 0;
}
Assert.IsTrue(IsAtExactInterval(new TimeSpan(10, 0, 0), new TimeSpan(1, 0, 0)));
Assert.IsFalse(IsAtExactInterval(new TimeSpan(10, 23, 0), new TimeSpan(1, 0, 0)));
When dealing with TimeSpan
s that are generated with the current date and time (such as DateTime.Now.TimeOfDay
), you might want to round the value first:
static TimeSpan Round(TimeSpan value, TimeSpan valueToRoundTo)
{
long factor = (value.Ticks + (valueToRoundTo.Ticks / 2) + 1) / valueToRoundTo.Ticks;
return new TimeSpan(factor * valueToRoundTo.Ticks);
}
TimeSpan value = new TimeSpan(10, 0, 25);
TimeSpan oneMinute = new TimeSpan(0, 1, 0);
TimeSpan roundedValue = Round(value, oneMinute);
Assert.IsTrue(new TimeSpan(10, 0, 0), roundedValue);
Assert.IsTrue(IsAtExactInterval(roundedValue, new TimeSpan(1, 0, 0)));