rAm
rAm

Reputation: 309

How to get the lowest future time (after now) from list of times with the current time

How to get the lowest future time, after the current time.

Schedule Time :

06.00

12.30

17.45

Current Time:

10.20

The Schedule time are in

List<TimeSpan> lstDT 

TimeSpan CurrentTimeSpan = TimeSpan.FromTicks(DateTime.Now.Ticks);

var min = lstDT
  .Select(x => new { 
     diff = Math.Abs((x - CurrentTimeSpan).Ticks), 
     time = x })
   .OrderBy(x => x.diff)
   .Last()
   .time;

Expected answer is 12.30 (since 12.30 is the next time after 10.20). If the current time is 23:59 then the expected result is 6.00.

Thanks

Upvotes: 0

Views: 121

Answers (1)

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186668

I can see 4 issues with the current code; we have to

  1. Get rid of date part (TimeOfDay)
  2. Change Last into First
  3. Be careful with break of day: 1:00 is closer to 23:59 than 22:00 (we have to analyze two values: difference and difference over the midnight)
  4. Since we want future only we should drop Math.Abs (which makes past and future being equal) but put a condition

Implementation:

  List<TimeSpan> lstDT = new List<TimeSpan>() {
    new TimeSpan( 6,  0, 0), // pure times, no date parts
    new TimeSpan(12, 30, 0),
    new TimeSpan(17, 45, 0),
  };

  // Test Data:
  // DateTime current = new DateTime(2018, 10, 27, 11, 20, 0);
  // TimeSpan CurrentTimeSpan = TimeSpan.FromTicks(current.TimeOfDay.Ticks);

  // TimeOfDay - we don't want Date part, but Time only
  TimeSpan CurrentTimeSpan = TimeSpan.FromTicks(DateTime.Now.TimeOfDay.Ticks);

  // closest future time
  var min = lstDT
    .Select(x => new {
       // + new TimeSpan(1, 0, 0, 0) - over the midnight
       diff = x > CurrentTimeSpan 
         ? (x - CurrentTimeSpan).Ticks
         : (x - CurrentTimeSpan + new TimeSpan(1, 0, 0, 0)).Ticks,
       time = x })
    .OrderBy(x => x.diff)
    .First()              // <- First, not Last
    .time;

Upvotes: 1

Related Questions