Dates, Times, and Chrono

This section documents C++23 (ISO/IEC 14882:2024), as published by ISO/IEC JTC1/SC22/WG21 (wg21), verified against the freely available working draft N5046 (eel.is/c++draft) and cppreference.com.

This content was generated with the assistance of AI and should be verified against the working draft and cppreference.com before being relied on in production.

This section’s bibliography lists the reference material consulted while preparing these pages.

chrono::duration

A duration is a compile-time-checked span of time — a count plus a ratio (seconds, milliseconds, …​), so mixing units is either a safe implicit conversion or a compile error, never a silent unit mismatch:

#include <chrono>
#include <iostream>

int main() {
    using namespace std::chrono_literals;

    std::chrono::seconds s = 5s;
    std::chrono::milliseconds ms = s;             // implicit widening conversion: 5000ms
    // std::chrono::seconds bad = ms;              // error: narrowing (ms -> s) needs an explicit cast

    auto rounded = std::chrono::duration_cast<std::chrono::seconds>(1500ms);  // explicit: 1s (truncates)
    std::cout << s.count() << ' ' << ms.count() << ' ' << rounded.count() << '\n';
}

Clocks and time_point

A time_point is a point on a specific clock’s timeline — three standard clocks cover almost every need:

#include <chrono>

auto wallClock = std::chrono::system_clock::now();    // wall-clock time, convertible to calendar time; CAN
                                                          // jump (NTP sync, manual change) -- not for measuring
                                                          // elapsed durations
auto monotonic = std::chrono::steady_clock::now();      // never jumps backward -- the right clock for measuring
                                                          // elapsed time/timeouts
auto highRes = std::chrono::high_resolution_clock::now(); // often an alias for one of the above; prefer
                                                             // steady_clock explicitly when steadiness matters

Measuring Execution Time

#include <chrono>
#include <iostream>
#include <thread>

int main() {
    auto start = std::chrono::steady_clock::now();
    std::this_thread::sleep_for(std::chrono::milliseconds(10));
    auto end = std::chrono::steady_clock::now();

    auto elapsed = std::chrono::duration_cast<std::chrono::microseconds>(end - start);
    std::cout << elapsed.count() << " microseconds\n";
}

Calendars: year_month_day

C++20 added a full calendar library on top of chrono, replacing manual day/month/year arithmetic and the error-prone struct tm:

#include <chrono>
#include <iostream>

int main() {
    using namespace std::chrono;

    year_month_day today{2024y, January, 15d};
    year_month_day lastDay = today.year() / today.month() / last;   // last day of that month
    std::cout << static_cast<unsigned>(lastDay.day()) << '\n';            // 31

    sys_days asDays = today;                                          // convert to a time_point at midnight
    sys_days nextWeek = asDays + days{7};
    year_month_day nextWeekYmd = nextWeek;
    std::cout << static_cast<unsigned>(nextWeekYmd.day()) << '\n';         // 22
}

Time Zones

`<chrono>’s time-zone database (C++20) converts between UTC and a named IANA zone — no more manually applying UTC offsets:

#include <chrono>
#include <iostream>

int main() {
    using namespace std::chrono;
    // requires a populated IANA tzdata database on the host system
    const time_zone* newYork = locate_zone("America/New_York");
    zoned_time zoned{newYork, system_clock::now()};
    std::cout << zoned << '\n';
}
the time-zone database requires the platform’s IANA tzdata (or the bundled fallback, depending on standard-library configuration) to actually be installed — verify with a small test program before relying on it in a deployed environment, as availability varies by OS/container image.

Formatting and Parsing Times

std::format/std::chrono compose directly via std::formatter specializations the library already provides for chrono types:

#include <chrono>
#include <format>
#include <iostream>

int main() {
    using namespace std::chrono;
    year_month_day date{2024y, March, 5d};
    std::cout << std::format("{:%Y-%m-%d}", date) << '\n';    // 2024-03-05

    auto duration = 90min;
    std::cout << std::format("{:%H:%M}", duration) << '\n';    // 01:30
}

See Also

  • C: Dates and Times — <time.h>, which <chrono> wraps in typed durations, clocks and calendars.