Pregunta

I have a TimeSpan variable that can be some time like 10:00:00 or some time like 10:23:00 And also I have another TimeSpan variable that is used to set the time interval, currently as default it is set on one hour intervals so 1:00:00

I am looking for a good way to determine if my timespan variable falls into my interval or not? For example if interval is every one hour then 10:00:00 is ok because we have hours or 1,2,3,4,5,etc.. but 10:23:00 is not ok because we have 10 and 11 but not 10:23

Is there any built in .NET way to determine this? if there is not then what is a good way to determine this.

¿Fue útil?

Solución 2

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 TimeSpans 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)));

Via: Rounding DateTime objects

Otros consejos

Your function requires a start time, as a datetime, an interval, and then a datetime to test. To see if the test value is some multiple of the given interval with respect to the given start time, you can simply compute a timespan between the current and start time, and see if the remainder of those ticks when divided by the interval is zero.

public static bool IsOnTick(DateTime start, TimeSpan interval, 
    DateTime dateToTest)
{
    return (dateToTest - start).Ticks % interval.Ticks == 0;
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top