CKTIS / C++
%F and %R in C++ chrono: fixed UTC offsets vs named time zones
`%F` prints the date and `%R` prints hours and minutes in 24-hour format. They format the value you pass; time-zone rules belong to the conversion step.
Version: ISO C++23; implementation support may vary
Syntax
std::format("{:%F %R}", time_point)
std::chrono::zoned_time{std::chrono::locate_zone("Europe/Warsaw"), instant}With chrono formatting %F and %R, std::format("{:%F %R}", time_point) prints the date and time from a std::chrono value. %F is equivalent to %Y-%m-%d (year, month, day). %R is equivalent to %H:%M (zero-padded hours and minutes on a 24-hour clock). %R leaves out seconds without rounding. Neither specifier converts between time zones or prints a UTC offset.
std::chrono::sys_seconds represents an instant whose date and time are formatted in UTC. To display a fixed UTC+01:00 offset, the example adds std::chrono::hours{1} to the elapsed time since the epoch and constructs a std::chrono::local_seconds from the result. That value stores the local date and time without a zone or an offset. EU_WARSAW is only an application label: it is not an IANA identifier and does not apply daylight saving rules.
To apply Warsaw's rules, use std::chrono::zoned_time{std::chrono::locate_zone("Europe/Warsaw"), instant}. The IANA time-zone database determines the offset in effect at that instant, including daylight saving transitions. Lookup can throw std::runtime_error if the database is unavailable or the name is not found.
These facilities were standardized in C++20 and are part of ISO C++23, but standard-library support varies. The example needs chrono formatting but does not need a time-zone database.
Examples
#include <chrono>
#include <format>
#include <iostream>
int main() {
using namespace std::chrono;
const sys_seconds instant = sys_days{year{2024}/July/1}
+ hours{23} + minutes{30} + seconds{45};
const local_seconds fixed_local{instant.time_since_epoch() + hours{1}};
std::cout << std::format("UTC: {:%F %R}\n", instant)
<< std::format("EU_WARSAW (fixed UTC+01:00): {:%F %R}\n",
fixed_local);
}Result
UTC: 2024-07-01 23:30 EU_WARSAW (fixed UTC+01:00): 2024-07-02 00:30
Adding one hour to `2024-07-01 23:30:45` UTC gives `2024-07-02 00:30:45`. `%R` displays `00:30`. The second line shows the fixed-offset result, not a conversion using Warsaw's rules.
Related lessons
- C++ · Lesson 50 · Advanced · Version: 3
Sources
- C++ working draft — Formatting [time.format]
- C++ working draft — Local time [time.clock.local]
- C++ working draft — Time zones [time.zone]
- C++ working draft — Class template zoned_time [time.zone.zonedtime]
- C++ working draft — Time zone database access [time.zone.db.access]
- C++ working draft — Class tzdb [time.zone.db.tzdb]
- C++ Draft International Standard (N4860)