现在和下一小时之间的时间跨度?
现在是 8:30,我想找出从现在到下一个整小时 (9:00) 之间有多少秒。我想我只想 DateTime.Now.AddHours(1
) 但在我这样做之后,我认为我需要“地板”。如何获得该值?
谢谢。
It is 8:30 and I am trying to find out how many seconds there are between now and the next whole hour (9:00). I think I just want to DateTime.Now.AddHours(1
) but after I do that I think I need the "floor". How to get that value?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(11)
只需将一天中的时间(以小时为单位)向上舍入到下一个整数值:
Just round the time of day in hours up to the next integral value:
您不必乱搞天花板和地板。
DateTime.Hour
属性表示 DateTime 所表示的一天中的整小时(它是 0 到 23 之间的整数)。您可以使用它和DateTime。 Date
属性来去除您不需要的 DateTime 的组成部分(不到一小时的数据),然后根据需要进行减去以生成TimeSpan
。如果您想要以秒为单位的结果,您当然可以提取结果
TimeSpan
的TotalSeconds
部分。You don't have to mess around with ceilings and floors. The
DateTime.Hour
property represents whole hours (it is an integer beteen 0 and 23) of the time of the day represented by the DateTime. You can use this and theDateTime.Date
property to strip the components of the DateTime you don't want (sub-hour data) and then just subtract as necessary to produce aTimeSpan
.You can of course extract the
TotalSeconds
component of the resultingTimeSpan
if you want the result in seconds.//完全误读。完全重写
我只会做这样的事情
//Completely misread. Completely re-writing
I woudl just do something Like this
这似乎是最简单的:(
如果您想要整数 - 整数 - 然后在
DateTime.Now...
前面加上(int)
。This seems to be the most simple:
(if you want it in whole numbers - integer - then prefix
DateTime.Now...
with(int)
.所以你需要减去“剩余”分钟,找到差值,然后乘以 60,对吧?
So you'd need to subtract the 'remainder' minutes, find the difference, and multiply that by 60, right?
这个怎么样:
How about this:
怎么样:
或者(也许更清楚):
How about:
Or (maybe clearer):
更易读的版本:
A more readable version:
基本上,您正在构建一个新的日期时间,该日期时间是从现在开始一小时,没有分钟或秒,然后从中减去现在并得到结果。
Basically here you are building a new DateTime that is one hour on from Now, with no minutes or seconds, then you subtract Now from this and have your result.
我会 Timespan.Parse 08:30,向对象添加 1 小时,然后检索小时部分并使用 :00 作为分钟构建一个新字符串,并重新解析新字符串。可能有一种更有效的方法来做到这一点,但我发现这种技术易于阅读。
I would Timespan.Parse 08:30, add 1 hr to the object, then retrieve the hour part and build a new string with :00 as the minutes and reparse the new string. There may be a more efficient way to do this, but I find this technique clear to read.