Skip to content
Tutorials Center
My learning

Topics

Lesson 127 of 171 ยท Utilities

Dates, Times and Durations with chrono

Learn C++ std::chrono - durations and literals like 500ms, steady and system clocks, timing code, calendar dates with year_month_day, time zones, formatting and parsing.

Time shows up everywhere in real programs: timeouts, benchmarks, log timestamps, "due in 3 days", meeting times in another country. Doing it with plain integers ("is this 5000 milliseconds or seconds?") is a famous source of bugs. The <chrono> library solves this with types: a duration knows its unit, a time point knows its clock, and a date knows it's a date. Mixing them up is a compile error instead of a production incident.

<chrono> arrived in C++11 with durations, clocks and time points. C++20 added calendar dates, time zones, formatting and parsing, which make it a complete date-and-time library. In this lesson you'll use all of these, in that order. Everything lives in std::chrono; examples write using namespace std::chrono; inside main to keep the code readable, which is the one place a using-directive is widely accepted (never in a header).

Durations: amounts of time with a unit

A std::chrono::duration<Rep, Period> is a count (Rep, usually an integer) of ticks of a given length (Period, a compile-time fraction of a second). You rarely spell that template out, because the standard provides aliases: nanoseconds, microseconds, milliseconds, seconds, minutes, hours, and since C++20 days, weeks, months and years.

With using namespace std::chrono_literals; (also pulled in by using namespace std::chrono;) you get suffixes: 2h, 15min, 30s, 250ms, 10us, 5ns. A few rules make durations safe:

  • Converting to a finer unit is implicit and exact: milliseconds ms = 3s; gives 3000ms.
  • Converting to a coarser unit could lose information, so it doesn't compile implicitly. You choose how to round: duration_cast (truncates toward zero), floor, ceil or round.
  • Arithmetic across units just works: 1min + 30s is 90s, expressed in the finer unit.
  • count() returns the raw number. Call it only at the edges, when you hand a number to something that isn't chrono-aware.
C++ Durations, literals and conversions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Durations print with their unit suffix (90s, 1500ms, 168h). That alone makes log messages much clearer. A unit without a standard suffix prints its tick length in brackets instead: weeks{1} shows as 1[604800]s, meaning "1 tick of 604,800 seconds". Cast to days or hours first if that looks odd in your output.

Use chrono durations in your own function signatures: void retry(std::chrono::milliseconds delay) can be called as retry(2s) or retry(250ms), and the caller can never pass "seconds" where milliseconds are expected by accident.

Clocks and time points

A clock provides now(), which returns a time_point<Clock, Duration>: a duration measured from the clock's epoch. Subtracting two time points of the same clock gives a duration; adding a duration to a time point gives a new time point. Adding two time points makes no sense and doesn't compile.

The clocks you'll use:

Clock Use it for Notes
steady_clock measuring intervals, timeouts never goes backwards; epoch is arbitrary (often boot time)
system_clock wall-clock time, timestamps, dates Unix time (UTC, since 1970-01-01); can jump when the system time is adjusted
high_resolution_clock nothing, in practice just an alias for one of the two above; prefer naming the one you mean
utc_clock, tai_clock, gps_clock, file_clock (C++20) specialist needs utc_clock counts leap seconds; file_clock is used by std::filesystem

The key rule: measure elapsed time with steady_clock, never with system_clock. If the computer's time is corrected by network time sync while your code runs, a system_clock measurement can come out negative or hours long.

C++ Measuring elapsed time

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The times you see change from run to run: the program shares a server with others, and sleep_for only promises to sleep at least as long as you ask. When you benchmark seriously, repeat the measurement many times and look at the minimum or median, and keep the compiler from optimizing away the work (here we print the result). Writing Fast C++ goes deeper.

std::this_thread::sleep_for(duration) and sleep_until(time_point) come from <thread> and take chrono types, as do the timeouts of mutexes, condition variables and futures. Once you think in chrono types, all of these APIs fit together.

Calendar dates (C++20)

C++20 added types for civil calendar dates: year, month, day, weekday, and combinations such as year_month_day. You can write dates with the / operator, in year/month/day, month/day/year or day/month/year order, as long as the first part's type makes the order clear: 2026y/October/17, October/17d/2026.

Two types do most of the work:

  • year_month_day is a "field" type, good for reading and printing year, month and day.
  • sys_days is a time point counting days since 1970-01-01 (a time_point<system_clock, days>). It's ideal for arithmetic: adding days, finding the difference between dates, getting the weekday.

The two convert back and forth implicitly, so the pattern is: convert to sys_days to compute, convert back to year_month_day to display.

C++ Working with calendar dates

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

ok() is the date library's validity check, and even the formatter notices: an invalid date prints as 2026-02-31 is not a valid date. Building a date like 2026y/February/30 is allowed (it's just three numbers), but ok() is false, and converting an invalid date to sys_days gives an unspecified result. Always check ok() on dates that come from user input or month arithmetic.

Note the conversions: year, month and day don't convert to numbers implicitly, which prevents mixing up day 3 and month 3. Use int(y), unsigned(m) and unsigned(d) when you really need the number.

Formatting and parsing

std::format and std::println understand every chrono type. With an empty {} you get a sensible default (2026-10-17, 90s, 2026-10-17 08:30:00). Inside the braces, % conversion specifiers choose exactly what to show, much like the C strftime function:

Specifier Meaning Example
%Y %m %d year, month, day (zero-padded) 2026 10 17
%F same as %Y-%m-%d 2026-10-17
%H %M %S hour (24 h), minute, second 08 30 00
%T / %R %H:%M:%S / %H:%M 08:30:00 / 08:30
%A %a weekday name, abbreviated Saturday Sat
%B %b month name, abbreviated October Oct
%j day of the year 290
%Z %z time zone abbreviation, offset UTC +0000

The reverse is std::chrono::parse(format, value), used with an input stream. It sets the stream's fail bit when the text doesn't match.

C++ Formatting and parsing timestamps

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The input box holds two lines; the second one fails to parse on purpose, so you can see the error path. Printing system_clock::now() without flooring shows fractional seconds (2026-10-17 08:30:00.123456789), because the default format shows the full precision of the time point.

Time zones (C++20)

system_clock time is UTC. To show a time the way people in a city see it, combine it with a time zone from the IANA time zone database (the same Europe/Berlin, America/New_York names used by every operating system):

  • std::chrono::locate_zone("Asia/Tokyo") finds a zone, throwing std::runtime_error for unknown names.
  • std::chrono::current_zone() is the computer's configured zone.
  • zoned_time{zone, sys_time} pairs a zone with a UTC instant. Formatting it shows local time; get_local_time() and get_sys_time() give each side.

Zones handle daylight saving time for you: the same zone has different offsets in winter and summer.

C++ One instant in several time zones

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Our server's clock is set to Etc/UTC, which is typical for servers; your own computer reports its local zone. Time zone support needs the tz database, which compilers find in different places: GCC's library reads the system's files and falls back to a built-in copy, while Microsoft's library uses Windows' ICU data. Older standard libraries (GCC before version 14, and Clang's libc++ until its recent releases) lack time zones or ship them only partially; the free Howard Hinnant "date" library, on which the standard design is based, fills that gap.

Best practices and pitfalls

  • Keep time in chrono types from the moment you read it until you print it. Convert to raw counts only for APIs that need numbers.
  • Store and compute in UTC (sys_time), convert to local time only for display. Local times can be ambiguous or nonexistent during DST changes.
  • steady_clock for intervals, system_clock for timestamps. Don't mix their time points; subtracting them doesn't compile, which is a feature.
  • Watch integer truncation. duration_cast<seconds>(1999ms) is 1s. Use round when you want the nearest value, or duration<double> for fractions.
  • Validate dates with ok(), especially after adding months or years.
  • Old C APIs (time(), localtime(), strftime()) still work, but localtime isn't thread-safe and returns a pointer to shared static data. You'll see them in older code; the <chrono> versions replace them.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does std::chrono::duration_cast<std::chrono::seconds>(2900ms) give?

    duration_cast truncates toward zero. Use round<seconds> for 3s, or duration<double> to keep 2.9s.
  2. 2. Which line does NOT compile?

    Converting milliseconds to seconds could lose information, so it requires an explicit duration_cast, floor, ceil or round. The other conversions are exact or floating-point.
  3. 3. You want to measure how long a function takes. Which clock should you use?

    system_clock can jump when the system time is adjusted. high_resolution_clock is only an alias and may be system_clock. steady_clock is made for intervals.
  4. 4. auto d = 2026y/January/31 + months{1}; What is d.ok()?

    Month arithmetic only changes the month field, giving 2026-02-31, which is not a valid date. Check ok() and clamp to the last day if needed.
  5. 5. A time point is stored as sys_seconds (UTC). How do you show it as local time in Tokyo?

    zoned_time applies the zone's rules, including any daylight saving time changes. Adding a fixed offset breaks in zones that change offsets during the year.

Summary

  • Durations (seconds, milliseconds, days, ...) carry their unit; literals like 500ms need std::chrono_literals. Lossless conversions are implicit; lossy ones need duration_cast, floor, ceil or round.
  • steady_clock::now() differences measure elapsed time; system_clock gives UTC wall-clock time; time point minus time point is a duration.
  • C++20 calendar types: write 2026y/October/17, compute with sys_days, display with year_month_day, and check ok().
  • std::format/std::println print chrono types directly, with %F, %T, %A and friends; std::chrono::parse reads them back.
  • zoned_time and locate_zone convert UTC to local time with daylight saving rules; store UTC, display local.

Next: Random Numbers, where you'll replace rand() with engines and distributions that give you real control.