[英]C++ arithmetic on time intervals
I already have working (ugly) code for this, but I will ask anyway: 我已经为此工作了(丑陋的)代码,但是无论如何我都会问:
I have the time intervals [09:15, 10:00), [21:10, 21:45) during weekdays. 我在工作日有时间间隔[09:15,10:00),[21:10,21:45)。 Given time
t
and a number of seconds s
, if t
is within the intervals, I have to calculate the date and time where t - s
would fall into. 给定时间
t
和秒数s
,如果t
在间隔内,我必须计算t - s
所属的日期和时间。
Is there a way of doing this in C++ cleanly (boost::icl? boost::date_time?) 有没有办法在C ++中做到这一点(boost :: icl?boost :: date_time?)
I have tried boost::icl, it can certainly hold the time ranges in an interval_set<Time>
and find which interval a certain Time
is in, but if t - s
time point does not fall into an interval range, I don't see how I can find the nearest interval before that time point, and how to detect if I have to go back a day or through the whole weekend. 我已经尝试过boost :: icl,它当然可以将时间范围保存在
interval_set<Time>
并找到某个Time
在哪个间隔中,但是如果t - s
时间点不属于一个间隔范围,我就不会看看如何找到该时间点之前的最近间隔,以及如何确定我是否必须回到前一天或整个周末。
I think the problem is too complicated to allow for a clean solution, at least according to my definition of "clean". 我认为这个问题太复杂了,以至于至少要按照我对“干净”的定义,不能提供一个干净的解决方案。
You'll need a container for your (non-overlapping) daily intervals, supporting efficiently the following operations: 您将需要一个容器来存放(不重叠)的每日时间间隔,以有效支持以下操作:
It seems to me that boost::icl::interval_set<Time>
is an adequate solution. 在我看来,
boost::icl::interval_set<Time>
是一个适当的解决方案。 Your time does not need to keep track of the date, you can have that separately. 您的时间不需要跟踪日期,可以单独设置日期。
Your algorithm will be something like: 您的算法将类似于:
let d and t be the date and time portions of your t
let i be the interval where t belongs
loop
if t-s belongs in i then
return t-s on day d
else
let j be the previous interval from i
if j does not exist (because i was the first) then
let j be the last interval
move d one weekday backwards
s := s - (t-start(i))
t := end(j)
i := j
This is more or less what you say that your code does. 这或多或少就是您所说的代码所做的。 I don't think it can be much cleaner.
我认为这不会更干净。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.