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 ?
CodePudding user response:
You're wanting to works with times of day. The TimeSpan
data type works with time spans (somewhat obvious to say). These are distinct concepts.
Times of day are precisely what motivated the creation of the new TimeOnly
type in .NET 6. It has an IsBetween
method:
Determines if a time falls within the range provided. Supports both "normal" ranges such as 10:00-12:00, and ranges that span midnight such as 23:00-01:00.
Note that IsBetween
use the more sensible convention of inclusive start, exclusive end which means that you'd use 01:00
as the to moment and not accidentally exclude e.g. 00:59:17
from your period
For older versions, I'd suggest you realise that if To
is less than From
(e.g. it's representing a period that crosses midnight) you should check:
if ((tsTo > tsFrom && dateObject >= tsFrom && dateObject < tsTo) ||
(tsFrom > tsTo && (dateObject < tsTo || dateObject >= tsFrom)))
{
}
Note, again, that this logic is assuming inclusive From
and exclusive To
(Your original logic treated both ends as exclusive which is rarely correct)
CodePudding user response:
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
}