iNCEPTiON_
iNCEPTiON_

Reputation: 621

C# Find Closest Time greater than DateTime.Now

Im struggling to get my little function to work.

What I'm trying to do:

I have an ObservableCollection of parsed DateTimes like

{"13:00","14:00,"17:00","22:00","22:00"}

and i want the closest time greater than the current DateTime.Now.

Code:

private DateTime GetNearestTime() {

    var nearestTime= (from x in TimeCollection
                      where x.MyTimeProperty.Ticks > DateTime.Now.Ticks
                      orderby x.MyTimeProperty.Ticks ascending
                      select x).First();
    return nearestTime;
}

What I'm getting is 1 value greater than the expected value.

Edit:

values for better understanding

var now = DateTime.Now.TimeOfDay // {18:32:35.4378850}

DateTime.TimeOfDay values in the collection.

[0:] 03:03:00
[0:] 05:03:00
[0:] 13:01:00
[0:] 17:16:00
[0:] 17:16:00
[0:] 23:01:00

The Collection is of type:

public class TimeData 
{
   public DateTime MyTimeProperty {get;set;}
}

Upvotes: 1

Views: 651

Answers (1)

D Stanley
D Stanley

Reputation: 152521

If you don't care about the date portion, then TimeOfDay is the appropriate property to compare:

private DateTime GetNearestTime() 
{
    var now = DateTime.Now.TimeOfDay;
    var nearestTime= (from x in TimeCollection
                      where x.MyTimeProperty.TimeOfDay > now
                      orderby x.MyTimeProperty.TimeOfDay ascending
                      select x).First();
    return nearestTime;
}

The Ticks property is documented as:

The value of this property represents the number of 100-nanosecond intervals that have elapsed since 12:00:00 midnight, January 1, 0001 (0:00:00 UTC on January 1, 0001, in the Gregorian calendar), which represents DateTime.MinValue. It does not include the number of ticks that are attributable to leap seconds.

Upvotes: 3

Related Questions