Time and dates in C++: chrono, clocks and testable time
Durations and clocks with std::chrono, passing the current time in so tests control it, times of day across midnight, and validating calendar dates with leap years.
Time looks simple until a test fails only at midnight. These are the habits that keep time code correct and testable.
Durations
std::chrono gives durations a unit in the type, so you can't add seconds to milliseconds by
mistake:
using namespace std::chrono_literals;
std::chrono::milliseconds timeout = 250ms;
auto total = timeout + 2s; // 2250ms: units convert safely
auto whole_seconds = std::chrono::duration_cast<std::chrono::seconds>(total); // 2s, truncatedIf a project's interface uses plain integers (std::int64_t now_ms), put the unit in the name,
always: now_ms, timeout_ms, minutes.
Time points and clocks
A time point is a duration since a clock's starting point.
std::chrono::steady_clock: never goes backwards. Use it for timeouts and measuring.std::chrono::system_clock: the wall clock. It can jump when the system time is corrected.
const auto deadline = std::chrono::steady_clock::now() + 500ms;
// later: condition_variable::wait_until(lock, deadline, predicate)Waiting until a deadline instead of "for 500 ms" each time means spurious wake-ups don't extend the total wait. See waiting with a deadline.
Pass the clock in
Code that calls now() inside its logic can only be tested by sleeping, which is slow and flaky.
Instead, make the current time an input:
class TokenBucket {
public:
bool try_acquire(std::int64_t now_ms); // the caller says what time it is
};
TokenBucket bucket(/*capacity*/ 2, /*ms_per_token*/ 1000, /*now_ms*/ 0);
CHECK(bucket.try_acquire(0));
CHECK(bucket.try_acquire(0));
CHECK_FALSE(bucket.try_acquire(500)); // half a token isn't enough
CHECK(bucket.try_acquire(1000));In production, the caller passes the real clock's value. The tests run in microseconds and never flake. That's how rate limiting for Gatekeep works. Also decide what happens if time appears to go backwards (a caller bug, or a clock correction): usually, treat it as no time passing.
Times of day and crossing midnight
Convert "HH:MM" to minutes since midnight and do the arithmetic on integers:
int minutes(int hh, int mm) { return hh * 60 + mm; }
int stay_length(int entry, int exit) {
return exit >= entry ? exit - entry : exit + 24 * 60 - entry; // crossed midnight
}Decide what entry == exit means (zero minutes, or a full day?) and write the test for it.
Validate the input strictly: "24:00", "7:5" and "12:60" are the cases tickets ask about. See
parking fees for ParkPoint.
Calendar dates and leap years
To validate YYYY-MM-DD, check the format character by character first, then the ranges:
bool is_leap(int y) { return (y % 4 == 0 && y % 100 != 0) || y % 400 == 0; }
int days_in_month(int y, int m) {
static constexpr int days[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
return m == 2 && is_leap(y) ? 29 : days[m - 1];
}2024 is a leap year, 1900 isn't, 2000 is. Those three belong in your tests.
To compare dates, you don't need a date library: a struct of {year, month, day} compared with
std::tie(a.year, a.month, a.day) < std::tie(b.year, b.month, b.day) sorts correctly, and so
does the YYYY-MM-DD string itself. To count days between dates, convert each to a day number
first (C++20's std::chrono::sys_days does this where your compiler supports it).
See the task list behind Tasklane.
Questions and answers
- steady_clock or system_clock?
- steady_clock for measuring how long something took or waiting with a timeout: it never jumps. system_clock for 'what time is it' as shown to people, which can jump when the computer's clock is corrected.
- How do I test code that depends on the current time?
- Don't call the clock inside the logic. Pass the time in as a parameter (or an injected clock object), so tests can say 'now it is 10:00, now it is 10:05' and get the same result every run.
Practise it in a project
These projects put this guide to work, with tickets, tests and code review.
Gatekeep
Rate limiting for Gatekeep
Protect Gatekeep's customers from traffic floods with token buckets: exact integer refills, a testable clock, per-client limits and bounded memory.
- token buckets
- injected time
- integer arithmetic
- memory bounds
ParkPoint
Parking fees for ParkPoint
Compute what ParkPoint's pay machines charge: stays across midnight, a free grace period, a daily cap and an evening flat rate.
- time arithmetic
- integer rounding
- business rules
- boundary testing
Tasklane
The task list behind Tasklane
Build the core of Tasklane's to-do list: strict due dates, stable task IDs and an agenda in the right order.
- date validation
- enums
- stable IDs
- multi-key sorting
Relaybox
A message queue for Relaybox
Build the bounded, blocking, closable queue between Relaybox's receivers and senders: mutexes, condition variables, backpressure, shutdown, timeouts and batches.
- threads
- mutexes
- condition variables
- backpressure
Read next
- Working with intervals: half-open ranges, overlaps, merging and gaps
Bookings, shifts, diff hunks and time slots are intervals. Use half-open ranges, test overlap with one comparison, check clashes in O(log n), merge overlapping intervals and find free gaps.