需要时间数学指导
我有一个日期时间对象,时间为上午 10:00 该时间代表一天中应该运行报告的时间。
我想计算从现在到上午 10:00 的剩余时间量,
我的部分困惑是现在可能是上午 10:00 之后或上午 10:00 之前,
我一直在玩 TimeSpan,但我的结果不太正确......我我确信这很简单,但这是我已经工作了几个小时的事情之一,我需要朝正确的方向推动...
我希望时间跨度对象 timeTillRun 是正确的...这就是我的已经尝试过:
{
DateTime scheduledRun = DateTime.Today.AddHours(_timeToStart);//_timeToStart = 10
TimeSpan timeTillRun = DateTime.Now - scheduledRun;
}
I have a DateTime object that is 10:00 AM
This time represents what time of day a report should be run.
I want to calculate the amount of time remaining from NOW until 10:00 AM
part of my confusion is NOW might be after 10:am or BEFORE 10am,
I keep playing around with TimeSpan, but my results are not quite right... I am sure this is simple, but it is one of those things I have been working of for a few hours and I need a push in the right direction...
I want the timespan object timeTillRun to be correct...here is what I have tried:
{
DateTime scheduledRun = DateTime.Today.AddHours(_timeToStart);//_timeToStart = 10
TimeSpan timeTillRun = DateTime.Now - scheduledRun;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这会起作用...但您需要颠倒减法的顺序:
请注意,如果当前是上午 10 点之后,
timeTillRun
将为负数。您可能还需要检查当前时间是否为上午 10 点或之后,然后向DateTime.Today
添加 10 小时和一天以获得下一次运行时间。或者,您可以测试timeTillRun
是否为负数;如果是这样,只需添加一天 (timeTillRun += new TimeSpan(1, 0, 0, 0)
)。This will work... but you need to reverse the order of subtraction:
Note that if it's currently after 10AM,
timeTillRun
will be negative. You will presumably also need to check if the current time is on or after 10AM, then add 10 hours and one day toDateTime.Today
to obtain the next run time. Alternatively, you could test iftimeTillRun
is negative; if so, just add one day to it (timeTillRun += new TimeSpan(1, 0, 0, 0)
).试试这个
Try this