Featured image of post 【C++20】std::chronoとstd::formatで現在時刻をUTCのISO 8601形式で出力する

【C++20】std::chronoとstd::formatで現在時刻をUTCのISO 8601形式で出力する

C++20のstd::chronoとstd::formatを使い、現在時刻をUTCのISO 8601形式で出力する完全なコード例と、処理系ごとの対応状況を解説します。

前提

  • ISO C++ 20 標準 (/std:c++20)

コード

この例はUTC時刻を秒単位でISO 8601形式(例: 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 は日付、%T は時刻を表します。書式中の T と Z はリテラルで、system_clock の時刻をUTCとして表します。実際には小数秒が付く場合があります。std::chrono の日時フォーマットはC++20ライブラリの機能ですが、標準ライブラリによって実装状況が異なります。利用するコンパイラと標準ライブラリの対応を確認してください。

参考

Licensed under CC BY-NC-SA 4.0
最終更新 2026/11/23 00:00 UTC
comments powered by Disqus