![](/img/trans.png)
[英]Is there a standard way to convert a std::string to std::chrono::time_point without using Boost?
[英]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
在这里找到。 它是一个只有头文件的库,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>{});
}
仅使用标准库头文件:
#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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.