0

Hello I've been trying to figure out how to tell if a DateTimeOffset is an interval of a timespan.

For example: if you have a date of something like: I've found a solution that works sometimes, but throw an errors others.

var bigTickTimeSpan = new TimeSpan(0, 30, 0);
Func<DateTime, bool> isBigTick = (time) => time.Minute % bigTickTimeSpan.Minutes == 0;

var notAnInterval = new DateTime(2022,11,18,9,31,0);

var interval = new DateTime(2022,11,18,9,30,0);
Console.WriteLine(isBigTick(notAnInterval));
Console.WriteLine(isBigTick(interval));

but the issue is we get a divide by 0 when we have

bigTickTimeSpan = new TimeSpan(1,0,0);
var thisThrowsError = isBigTick(new DateTime(2022,11,18,9,0,0)); 

How can I check if its an interval of the timespan regardless of which timespan I want to use?

UPDATE

What I'm trying to accomplish is if we have a TimeSpan.FromMinutes(5) when a time is passed in isBigTick should be true if the minute is 9:00,9:05,9:10 and so on. If we pass in TimeSpan.FromSeconds(5), isBigTick should be true 9:00:00, 9:00:05, 9:00:10,...,9:59:55. any interval of 5 seconds.

3
  • It is not very clear what you want to do. The issue you have is that new TimeSpan(1, 0, 0).Minutes gives you 0, which triggers the divide by zero exception. You can investigate using bigTickTimeSpan.TotalMinutes, which would result in a % 60. Production code like that should check for zero anyway, in my book, so you should decide what happens when isBigTick gets called with TimeSpan.Zero. It is more a matter of deciding what should happen than implementing it. Personally, I would write a unit test first, for this kind of code. Commented Nov 18, 2022 at 16:49
  • In other words: what exactly ` its an interval of the timespan` means? You could just pass in the number of minutes you want to check. Commented Nov 18, 2022 at 16:50
  • Use the .Ticks. Commented Nov 18, 2022 at 16:56

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.