如何从当前时间的时间列表中获取最低的未来时间(现在之后)

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

如何获得当前时间之后的最低未来时间。

安排时间

06.00

12.30

17.45

当前时间:

10.20

预定时间在

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;

预期答案是 12.30(因为 12.30 是下一次 10.20 之后)。 如果当前时间是 23:59 那么预期结果是 6.00。

谢谢

我发现当前代码存在 4 个问题;我们必须

  1. 删除 日期部分 (TimeOfDay)
  2. Last改成First
  3. 注意破晓1:0022:00更接近23:59(我们必须分析两个值:差值和差值超过午夜)
  4. 因为我们只想要 future 我们应该放弃 Math.Abs (这使得过去和未来相等)但是放一个条件

实施:

  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;