Search code examples
c++c++20c++-chrono

C++20 chrono, parsing into zoned time and formatting without trailing decimals


I am writing a bit of code that intakes a string from a user, and formats it into a zoned time. The parsing code is a bit more complicated than this example, but this will reproduce problem.

This is compiled with MSVC++ compiled with /std:c++latest.

#include <iostream>
#include <string>
#include <chrono>
#include <sstream>

int main() {
    std::string timeString("2020-02-03 00:12:34");
    std::string formatString("%Y-%m-%d %T");

    bool successful = true;
    std::stringstream iss(timeString);
    std::chrono::local_time<std::chrono::system_clock::duration> localTimeStamp;
    if (not (iss >> std::chrono::parse(formatString, localTimeStamp))) {
        successful = false;
    }
    auto result = std::chrono::zoned_time(std::chrono::current_zone(), localTimeStamp);

    std::cout << std::format("{:%Y-%m-%d %T}", result) << std::endl;
}

Results in the following output:

2020-02-03 00:12:34.0000000

I would like for the output to not have the trailing decimals. Since it's a string, I can always truncate the string at the decimal anyway. Is there a better way to do this?


Solution

  • Just change the type of localTimeStamp to have seconds precision:

    std::chrono::local_time<std::chrono::seconds> localTimeStamp;
    

    There's also this convenience type-alias to do the same thing if you prefer:

    std::chrono::local_seconds localTimeStamp;
    

    The precision of the parsing and formatting is dictated by the precision of the time_point being used.