将 time_point 转换为字符串的最漂亮方法是什么?
What is the prettiest way to convert time_point to string?
简单的问题,如何使用尽可能少的代码正确地将 std::chrono::time_point
转换为 std::string
?
注意:我不想将 cout
与 put_time()
一起使用。接受 C++11 和 C++14 解决方案。
#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
被发现 here. It is a header-only library, C++11/14/17. It has written documentation, and a video introduction.
更新:
在 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>{});
}
仅使用标准库头文件(适用于 >= 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);
简单的问题,如何使用尽可能少的代码正确地将 std::chrono::time_point
转换为 std::string
?
注意:我不想将 cout
与 put_time()
一起使用。接受 C++11 和 C++14 解决方案。
#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
被发现 here. It is a header-only library, C++11/14/17. It has written documentation, and a video introduction.
更新:
在 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>{});
}
仅使用标准库头文件(适用于 >= 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);