簡體   English   中英

將 time_point 轉換為字符串的最佳方法是什么?

[英]What is the prettiest way to convert time_point to string?

簡單的問題,如何用盡可能少的代碼將std::chrono::time_point正確轉換為std::string

注意:我不想將coutput_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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM