将 time_point 转换为字符串的最佳方法是什么?

dra*_*ita 5 c++ string c++11 c++-chrono c++14

简单的问题,如何以尽可能少的代码正确转换std::chrono::time_point为 a std::string

注意:我不想将cout它与put_time(). 接受 C++11 和 C++14 解决方案。

StP*_*ere 6

仅使用标准库头文件(适用于 >= C++11):

    #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);
Run Code Online (Sandbox Code Playgroud)


How*_*ant 5

#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>, "");
}
Run Code Online (Sandbox Code Playgroud)

date/date.h在这里找到的。它是一个仅包含头文件的库,C++11/14/17。它有书面文档视频介绍

更新:

在 C++20 中,语法为:

#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>{});
}
Run Code Online (Sandbox Code Playgroud)