Featured image of post [C++20] Format the Current Time as UTC ISO 8601 with std::chrono and std::format

[C++20] Format the Current Time as UTC ISO 8601 with std::chrono and std::format

A complete C++20 example that formats the current time as UTC ISO 8601 with std::chrono and std::format, plus notes on standard-library support.

Prerequisites

  • ISO C++ 20 Standard (/std:c++20)

Code

This example formats UTC to whole-second precision, for example 2026-11-23T00:00:00Z.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
#include <chrono>
#include <format>
#include <iostream>
#include <string>

int main() {
    const auto now = std::chrono::floor<std::chrono::seconds>(
        std::chrono::system_clock::now());
    const std::string datetime = std::format("{:%FT%TZ}", now);
    std::cout << datetime << '\n';
}

%F formats the date and %T the time. The T and Z in the format string are literal characters; the system_clock time point is formatted as UTC. Fractional seconds may appear if the time point has subsecond precision. Chrono formatting is a C++20 library feature, but implementation support varies by standard library. Check the compiler and library you use.

References

comments powered by Disqus