Search code examples
c++stringc++11c++14c++-chrono

What is the prettiest way to convert time_point to string?


Simple question, how to properly convert std::chrono::time_point to a std::string with as little code as possible?

Notes: I don't want to use cout it with put_time(). C++11 and C++14 solutions are accepted.


Solution

  • #include "date/date.h"
    #include <type_traits>
    
    int
    main()
    {
        auto s = date::format("%F %T", std::chrono::system_clock::now());
        static_assert(std::is_same<decltype(s), std::string>, "");
    }
    

    date/date.h is found here. It is a header-only library, C++11/14/17. It has written documentation, and a video introduction.

    Update:

    In C++20 the syntax is:

    #include <chrono>
    #include <format>
    #include <type_traits>
    
    int
    main()
    {
        auto s = std::format("{:%F %T}", std::chrono::system_clock::now());
        static_assert(std::is_same_v<decltype(s), std::string>{});
    }