skip to content

With C++20's std::chrono calendar and time-zone types, how do you turn a local wall-clock time into UTC, and what happens in a DST gap?

level: seniorimportance: should knowfreq 28%

answer

  1. year_month_day, then local_days
  2. local_time has no zone yet
  3. time_zone::to_sys or zoned_time
  4. gap throws, overlap throws
  5. choose::earliest or choose::latest

basics

~20 s

Build a local_time from a date and a time of day, then convert it with a time_zone's to_sys or a zoned_time. A time skipped by a daylight-saving gap throws nonexistent_local_time, a repeated one throws ambiguous_local_time, unless you pass choose::earliest or choose::latest.

solid answer

~40 s

C++20 separates **calendar fields** from **time points**. `2026y / March / 29` is a `year_month_day`; it converts implicitly to `sys_days` and explicitly to `local_days`. Adding `2h + 30min` to a `local_days` gives a `local_time`, a wall-clock reading not yet tied to any zone. `std::chrono::locate_zone("Europe/Berlin")` returns a `const time_zone*` from the time-zone database, and `to_sys(local)` gives the UTC `sys_time`; `zoned_time{"Europe/Berlin", local}` does the same and keeps both views. When clocks spring forward, 02:30 does not exist and the conversion throws `nonexistent_local_time`; when they fall back, it occurs twice and throws `ambiguous_local_time`. Passing `choose::earliest` or `choose::latest` picks a result instead; for a gap both return the transition instant. Calendar arithmetic does not clamp: `2026y/January/31 + months{1}` is the invalid 2026-02-31, whose `ok()` is `false`.

code

cpp · 21 lines
cpp
#include <chrono>
#include <iostream>

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

    year_month_day billing = 2026y / January / 31;
    year_month_day next = billing + months{1};          // field arithmetic, no clamping
    std::cout << next << " ok=" << next.ok() << '\n';   // 2026-02-31 is not a valid date ok=0

    year_month_day_last eom = 2026y / February / std::chrono::last;
    std::cout << year_month_day{eom} << '\n';           // 2026-02-28

    sys_days day = 2026y / March / 1;                   // a count of days since 1970-01-01
    std::cout << year_month_day{day - days{1}} << ' '   // 2026-02-28
              << weekday{day} << '\n';                  // Sun

    local_days meeting{2026y / March / 29};             // explicit: a date in no zone yet
    auto wall = meeting + 2h + 30min;                   // local_time: 02:30 on that date
    std::cout << wall << '\n';                          // 2026-03-29 02:30:00
}

go deeper

for a junior

Recall that sys_time means UTC, that dates are built like 2026y/March/29, and that zones convert local time to UTC.

for a middle

Explain fields versus time points, why month arithmetic can produce an invalid date, and how to_sys and zoned_time are used.

for a senior

Show the gap and overlap failure modes, an explicit choose policy for scheduled work, and how to check library support for the zone database.

for a principal

Set the data model: instants stored as UTC, local rules applied at the edges, and a policy for daylight-saving transitions in scheduled jobs.

## Fields, points and zones C++20 (paper P0355) extended `<chrono>` with three layers that interviewers expect you to keep apart: | Layer | Types | Meaning | |---|---|---| | Calendar fields | `year`, `month`, `day`, `weekday`, `year_month_day`, `year_month_day_last` | a date as fields, possibly invalid | | Time points | `sys_days`, `sys_seconds`, `local_days`, `local_time<D>` | a count of days or seconds since 1970-01-01 | | Zones | `time_zone`, `zoned_time`, `tzdb`, `locate_zone`, `current_zone` | the rules that map local time to UTC | `sys_time` (a `system_clock` time point) means **UTC**. `local_time` uses the pseudo-clock `local_t`: it is a wall-clock reading **in no particular zone**, so it cannot be compared with `sys_time` until a zone is applied. ## Building dates - `2026y / March / 29` builds a `year_month_day` with the C++20 `y` literal and the `March` constant. - `year_month_day` converts **implicitly** to `sys_days` and **explicitly** to `local_days`; writing `local_days d = 2026y/March/29;` does not compile, `local_days d{2026y/March/29};` does. - `2026y / February / last` is a `year_month_day_last`, the end of that month, which resolves leap years for you. - `weekday{sys_days{...}}` gives the day of the week. Calendar arithmetic adds to **fields** and never clamps. `2026y/January/31 + months{1}` is `2026-02-31`; its `ok()` is `false`, and streaming it prints "2026-02-31 is not a valid date". To move by days, convert to `sys_days`, add `days{n}`, and convert back. To mean "same day next month, clamped", decide the policy yourself, typically with `year_month_day_last`. ## From local wall time to UTC ```cpp // C++20; needs a standard library built with the time-zone database using namespace std::chrono; const time_zone* berlin = locate_zone("Europe/Berlin"); local_time<minutes> wall = local_days{2026y / October / 1} + 9h + 30min; auto utc = berlin->to_sys(wall); // sys_seconds: 07:30 UTC, summer time zoned_time meeting{berlin, wall}; // keeps zone, local and sys views ``` `locate_zone` searches the **IANA time-zone database** that the library loads, and throws `std::runtime_error` if the name is unknown. `zoned_time` pairs a zone with a `sys_time` and gives `get_local_time()` and `get_sys_time()`. ## The two daylight-saving hazards Where a zone moves its clocks, some local times **do not exist** and others **occur twice**: 1. **Gap (spring forward).** On 2026-03-29 in `Europe/Berlin`, clocks jump from 02:00 to 03:00, so 02:30 never happens. `to_sys(wall)` and the `zoned_time` constructor from a `local_time` throw **`nonexistent_local_time`**. 2. **Overlap (fall back).** On 2026-10-25 clocks go from 03:00 back to 02:00, so 02:30 happens twice. The conversion throws **`ambiguous_local_time`**. Both exceptions derive from `std::runtime_error`. The overloads taking `choose` avoid them: in an overlap, `choose::earliest` returns the first occurrence and `choose::latest` the second; in a gap, the standard says both choices return the **same** UTC instant, the moment of the transition. The standard's own example shows the message for New York: ```plaintext 2016-03-13 02:30:00 is in a gap between 2016-03-13 02:00:00 EST and 2016-03-13 03:00:00 EDT which are both equivalent to 2016-03-13 07:00:00 UTC ``` ## Library support The calendar types are widely available, but the **time-zone database** needs library and platform support: - libstdc++ documents the C++20 calendar types from GCC 11.1 and time zones from GCC 13.1; - libc++ lists P0355 as **partial**, and gates the zone functions behind a configuration macro. The libc++ in Apple's SDK used for this answer compiles the calendar code in the example but reports `locate_zone` as an undeclared identifier, which is why the zone code above is shown as a fenced block and was not run. ## What to say in an interview - Store and compare instants as `sys_time` (UTC); convert to local time only to display or to interpret user input. - Decide the gap and overlap policy explicitly with `choose`, rather than letting a scheduled job throw once a year. - Validate calendar results with `ok()` after month or year arithmetic. ## Where the zone rules come from Zone rules change several times a year when governments move or abolish daylight saving. The standard models this with a **`tzdb_list`**: `get_tzdb()` returns the database currently in use, `remote_version()` reports the version the implementation could load, and `reload_tzdb()` loads a newer one and pushes it to the front of the list without invalidating pointers into older versions. A long-running service therefore keeps working with the rules it started with until something calls `reload_tzdb()`, and a container image with an old copy of the database converts future dates with old rules. Both are operational questions a senior candidate should raise.

  • Why does a year_month_day plus months{1} not clamp 31 January to 28 February?
    Calendar arithmetic in C++20 adds to the month field and keeps the day field unchanged; the standard notes the result is valid whenever the day is 1 to 28. Clamping, rolling into March or rejecting are all reasonable business rules, so the library leaves the choice to you and gives `ok()` to detect the invalid date and `year_month_day_last` to express end-of-month.
  • Should a recurring 02:30 local job be stored as sys_time or as local time plus zone?
    As local time plus zone, because the job is defined by the wall clock: it should run at 02:30 local time on every date, and its UTC instant changes with daylight saving. Convert each occurrence with `to_sys` and an explicit `choose` policy, so the gap day and the overlap day have a defined outcome instead of an exception.

  • local_time is UTC with a different name
  • January 31 plus one month gives February 28 automatically
  • a nonexistent local time is silently shifted by one hour
  • choose::earliest and choose::latest give different results in a gap
  • every standard library ships the time-zone database with C++20

Assumes the C++20 calendar and time-zone library (P0355); the zone database is a library feature whose availability varies, and the libc++ in Apple's SDK here lacks it.