头脑风暴:如何将 DateTime 安排到特定的间隔框架?
假设我有一个日期时间,例如 2010.12.27 12:33:58,并且我有一个间隔帧,假设为 2 秒,不包括最后一个边框。
所以,我有以下帧:
12:33:58(含)-12:34:00(不含) - 让它成为间隔 1
12:34:00(含)-12:34:02(不含) .) - 设为间隔 2
12:34:02(含)-12:34:04(不含) - 设为间隔 3
,依此类推。
我得到了一个随机的日期时间值,我必须根据上述规则关联该值。
例如值“12:33:58”属于区间 1,“12:33:59”属于区间 1,“12:34:00”属于区间 2,依此类推。
在代码中,它应该如下所示:
var dt = DateTime.Now;
DateTime intervalStart = apply_the_algorythm(dt);
这似乎是一些带有浮点数或其他内容的简单算术操作,欢迎任何决定!
Suppose i have a DateTime, e. g. 2010.12.27 12:33:58 and i have an interval frames of, suppose, 2 seconds, excluding the last border.
So, i have the following frames:
12:33:58(incl.)-12:34:00(excl.) - let it be interval 1
12:34:00(incl.)-12:34:02(excl.) - let it be interval 2
12:34:02(incl.)-12:34:04(excl.) - let it be interval 3
and so on.
I'm given a random DateTime value and i have to correlate that value according the above rules.
E. g. the value "12:33:58" falls into interval 1, "12:33:59" falls into interval 1, "12:34:00" falls into interval 2 and so on.
In code it should look like the following:
var dt = DateTime.Now;
DateTime intervalStart = apply_the_algorythm(dt);
It seems to be some simple arithmetic action(s) with float or something, any decisions are welcome!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
如果间隔只是秒分辨率并且始终除以 86400,则取今天经过的秒数,除以间隔,将其四舍五入为整数值,相乘,然后将其加回到今天。类似于 dateinquestion.Subtract(dateinquestion.Date).TotalSeconds、((int)秒/间隔)*间隔、dateinquestion.Date.AddSeconds(...)
If the interval is only second resolution and always divided 86400, then take the number of seconds that have passed today, divide it by the interval, round it to an integer value, multiply it, and add it back to today. Something like dateinquestion.Subtract(dateinquestion.Date).TotalSeconds, ((int)seconds/interval)*interval, dateinquestion.Date.AddSeconds(...)
如果您希望所有间隔的范围跨越几天,甚至可能很长一段时间,您可能需要在 UNIX 秒(自 1970-01-01 以来的秒数)。然后你只需找出你的第一个间隔何时开始,计算从那时起经过了多少秒,然后除以二:
否则你最好从午夜开始计数。
If you want the range of all your intervals to span several days, possibly a long time, you might want to express your
DateTime
values in UNIX-seconds (the number of seconds since 1970-01-01). Then you just find out when your very first interval started, calculate how many seconds passed since then, and divide by two:Otherwise you're better off just counting from midnight.
使用 TimeSpan.TotalSeconds 并将结果除以间隔的大小。
Use
TimeSpan.TotalSeconds
and divide the result by the size of the interval.