如何获取当前时间之后的最低未来时间。
计划时间:
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(因为下一次之后 10.20为12.30)。 如果当前时间是23:59,则预期结果是6.00。
谢谢
答案 0 :(得分:1)
我可以看到当前代码中的 4 个问题;我们必须
TimeOfDay
)Last
更改为First
1:00
比23:59
更接近22:00
(我们必须分析两个 值:午夜之间的差异和差异)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;