简体   繁体   中英

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.

#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>{});
}

Using only standard library headers:

    #include <ctime>
    #include <chrono>
    #include <string>

    using sc = std::chrono::system_clock ;
    std::time_t t = sc::to_time_t(sc::now());
    char buf[20];
    strftime(buf, 20, "%d.%m.%Y %H:%M:%S", localtime(&t));
    std::string s(buf);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM