[英]How to convert std::chrono::zoned_time to std::string
從std::chrono::zoned_time
轉換為std::string
的最有效方法是什么?
我想出了這個簡單的解決方案:
#include <iostream>
#include <sstream>
#include <string>
#include <chrono>
#if __cpp_lib_chrono >= 201907L
[[ nodiscard ]] inline auto
retrieve_current_local_time( )
{
using namespace std::chrono;
return zoned_time { current_zone( ), system_clock::now( ) };
}
#endif
int main( )
{
const std::chrono::zoned_time time { retrieve_current_local_time( ) };
const auto str { ( std::ostringstream { } << time ).str( ) };
std::cout << str << '\n';
}
可以看出,使用operator<<
將time
插入到ostringstream
對象中,然后從其內容構造一個std::string
。
標准庫中還有什么比這更好的嗎?
順便說一句,為什么上面的程序在 Compiler Explorer 上執行時沒有給出正確的輸出?
你所擁有的還不錯。 您還可以使用std::format
自定義時間戳的格式。 而std::format
直接返回一個std::string
:
const auto str = std::format("{}", time);
這給出了與你所擁有的相同的格式。
const auto str = std::format("{:%FT%TZ}", time);
這提供了另一種流行的 (ISO) 格式。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.