简体   繁体   English

时间间隔的C ++算术

[英]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所属的日期和时间。

  • Example: t = 20130913 21:15, s = 600, t - s falls into 20130913 09:55. 示例:t = 20130913 21:15,s = 600,t-s属于20130913 09:55。
  • Example: t = 20130923 09:16, s = 120, t - s falls into 20130920 21:44. 示例:t = 20130923 09:16,s = 120,t-s属于20130920 21:44。

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: 您将需要一个容器来存放(不重叠)的每日时间间隔,以有效支持以下操作:

  • find in which specific interval a given time belongs, 查找给定时间属于哪个特定间隔,
  • move an interval backwards, in the container, and 在容器中向后移动一个间隔,然后
  • move to the last interval (in chronological order). 移至最后一个间隔(按时间顺序)。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM