'Comparing timespan object if it's between hours in C#
I want to filter an array of objects. The goal is to filter the objects between two timespan objects:
TimeSpan tsFrom = TimeSpan.Parse("16:00");
TimeSpan tsTo = TimeSpan.Parse("00:59");
For example I have this object:
TimeSpan dateObject = TimeSpan.Parse("22:05:22");
The problem comes when I try to compare if the dateObject is between tsFrom and tsTo:
if (dateObject > tsFrom && dateObject < tsTo)
{
// do something ....
}
This won't work for cases like that. Do you have any ideas how I can make this work ?
Solution 1:[1]
The problem with this one is that you're trying to use the timeSpan method in the wrong way, if I got it right you are trying to check if the dateObject time comes between tsFrom and tsTo, the problem is that you are trying to refer to a different day with the tsTo, something that timespan can not handle. I fixed it using dateTime to specify at least the day the time is taken from, i suggest changing the code to this
string datevalue = @"15/03/2021 16:00:00";
DateTime start = DateTime.Parse(datevalue);
datevalue = @"16/03/2021 00:59:00";
DateTime end = DateTime.Parse(datevalue);
datevalue = @"15/03/2021 22:05:22";
DateTime obj = DateTime.Parse(datevalue);
if (obj > start && obj < end)
{
//Do something
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | sMuLe |
