1

I'm ceiling time_point to next full five minutes, which is quite easy:

template <int N>
    using minutes = std::chrono::duration<int, std::ratio_multiply<std::ratio<N>, std::chrono::minutes::period>>;

const auto now = std::chrono::system_clock::now();
const auto begin = ceil<minutes<5>>(now);

I don't know how to set the count of minutes at runtime.

oley
  • 21
  • 1
  • `std::chrono::minutes(X)`? – Some programmer dude Feb 08 '19 at 11:45
  • You'll have to do the arithmetic yourself. There is no chrono-supplied API to do this. – Howard Hinnant Feb 08 '19 at 19:01
  • What precision would you like to have the resultant `time_point` to have? I can see three reasonable answers: 1) The precision of the input `time_point` (`system_clock::duration` in this example). 2) The precision of the input `duration` (`minutes` in this example). 3) The `common_type` of 1) and 2) (`system_clock::duration` in this example). – Howard Hinnant Feb 09 '19 at 22:50
  • I just need to ceil to next round 5 minutes, without seconds, milliseconds... I need time_points in hour x -> x:00, x:05, x:10, ..., x:55 My example do what I want, but it's compile time solution, for e.g. ceiling to 10 or 1 I need to recompile it. – oley Feb 11 '19 at 08:25

1 Answers1

2

Here is a ceil function that will take any time_point and round it up to the next Duration m, while giving the result a precision of Duration{1}:

template <class Clock, class Duration1, class Duration2>
constexpr
auto
ceil(std::chrono::time_point<Clock, Duration1> t, Duration2 m) noexcept
{
    using R = std::chrono::time_point<Clock, Duration2>;
    auto r = std::chrono::time_point_cast<Duration2>(R{} + (t - R{})/m*m);
    if (r < t)
        r += m;
    return r;
}

It can be used like:

const auto begin = ceil(system_clock::now(), 5min);
const auto begin = ceil(system_clock::now(), 10min);
const auto begin = ceil(system_clock::now(), 10ms);
  1. First the return type is computed and given the alias R.
  2. Then the time_point t is truncated to the duration m (towards zero).
  3. If the truncated result is less than the input, the result is rounded up to the next m.

If 24 hours is not evenly divisible by m, the result may be counterintuitive.

Howard Hinnant
  • 206,506
  • 52
  • 449
  • 577