简体   繁体   English

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

[英]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?简单的问题,如何用尽可能少的代码将std::chrono::time_point正确转换为std::string

Notes: I don't want to use cout it with put_time() .注意:我不想将coutput_time() C++11 and C++14 solutions are accepted.接受 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 is found here . date/date.h这里找到。 It is a header-only library, C++11/14/17.它是一个只有头文件的库,C++11/14/17。 It has written documentation , and a video introduction .它有书面文档视频介绍

Update:更新:

In C++20 the syntax is:在 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>{});
}

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 有没有一种标准方法可以在不使用Boost的情况下将std :: string转换为std :: chrono :: time_point? - Is there a standard way to convert a std::string to std::chrono::time_point without using Boost? 如何在不使用数组的情况下将 chrono::time_point 转换为字符串? - how to convert chrono::time_point to string without using array? 将具有微秒精度的字符串转换为计时时间点 - Convert a string with micro second precision to a chrono time_point 如何将字符串转换回 time_point? - How do I convert a string back into a time_point? 如何将纪元时间转换为time_point - How to convert epoch time to time_point std :: string到std :: chrono time_point - std::string to std::chrono time_point std::time_point 从和到 std::string - std::time_point from and to std::string C++ 如何将日期从输入(字符串年、字符串月、字符串日)转换为 time_point - C++ How to convert date from input (string year, string month, string day) to time_point 使用 std::format 将 time_point 转换为字符串,格式包括日期、时间和亚秒 - Convert time_point to string using std::format with format that includes date, time and subseconds C ++将字符串时间戳转换为std :: chrono :: system_clock :: time_point - C++ Convert a string timestamp to std::chrono::system_clock::time_point
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM