Search code examples
c++datec++-chrono

how to format a UTC time string using howardhinnant's c++ date library


Can someone help me to format a date string using Howard Hinnant's excellent date/time library. I am trying to output a UTC date from the current time. The desired format of the date/time is zulu time per:

"2018-11-01T15:32:56Z" - i.e. "YYYY-MM-DDTHH:MM:SSZ" -

So far using Howard's documentation I was able to get the partial result to work as follows:

const auto today = floor<days>(system_clock::now());
auto dateTimeString = std::format("{}T{:02}:{:02}:{:02}Z", today, 15, 20, 59);

I had to hard code the HH MM & SS fields. I am sure there is an easy way to format a custom date/time in this library. Any help appreciated.


Solution

  • If you're using std::format, then you're using C++20, instead of Howard Hinnant's date/time library. Though the latter is the basis of the C++20 chrono library.

    Your code should look like:

    const auto today = floor<seconds>(system_clock::now());
    auto dateTimeString = std::format("{:%FT%T}Z", today);
    

    The variable today contains a UTC time point with a precision of seconds. Then {:%FT%T} formats the YYYY-MM-DDTHH:MM:SS part of it (%F for the date and %T for the time).