2

Let's say I have a stream of events, each event with a full timestamp, spanning many days. I want to compare them against the time of day, but regardless of the day. For example, if a given event happened between 12:00:00 and 12:05:00, do something, but regardless of the day.

The event timestamps naturally fit as std::chrono::time_point objects. What is the most idiomatic way within std::chrono to do those comparisons? Is there an object that represents a time-of-day without being specific to a day? Do I have to roll my own?

John S
  • 3,035
  • 2
  • 18
  • 29

2 Answers2

1

Is there an object that represents a time-of-day without being specific to a day? Do I have to roll my own?

I don't think so. But it should be trivial to implement. Convert the timepoint to the broken-down time std::tm, and then check the individual members.

#include <chrono>
#include <ctime>    // struct tm, gmtime()

using std::chrono::system_clock;

std::time_t ts = system_clock::to_time_t (system_clock::now());
std::tm& time = *gmtime (&ts);  // or localtime()

if (time.tm_hour==12 and time.tm_min>=0 and time.tm_min<5)
    cout << "Inside interval\n";

Note: gmtime() and localtime() return a pointer to static data and hence are not thread-safe. Linux (and probably other *nix) has the thread safe gmtime_r() and localtime_r().

1

You may do something like:

auto timePoint = std::chrono::system_clock::now();
std::time_t t = std::chrono::system_clock::to_time_t(timePoint);
auto ltime = std::localtime(&t); // or gmtime.
auto eventTime = std::chrono::hours(ltime->tm_hour)
    + std::chrono::minutes(ltime->tm_min);

auto lower_bound = std::chrono::hours(12) + std::chrono::minutes(0);
auto upper_bound = std::chrono::hours(12) + std::chrono::minutes(5);

if (lower_bound <= eventTime && eventTime <= upper_bound) {
    // Do some action.
}
Jarod42
  • 203,559
  • 14
  • 181
  • 302
  • Both good answers, though this one looks a little cleaner to my eye. I had been thinking there was some way to do this with a duration object, and it looks like that's what you've done in effect here, since I believe the bottom 3 auto variables resolve to exactly that. – John S Aug 03 '14 at 17:45