[英]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.