[英]std::time_point from and to std::string
我正在嘗試使用 c++20 std::chrono 替換一些 boost::gregorian 代碼,希望消除 boost 構建依賴。 代碼正在讀寫 json(使用 nlohmann),因此將日期與 std::string 相互轉換的能力至關重要。
在 Ubuntu 20.04 上使用 g++ 9.3.0。 2 個編譯時錯誤,一個在 std::chrono::parse() 上,第二個在 std::put_time()
對於 std::chrono::parse() 上的錯誤 A,我在這里看到包含 chrono::parse 的日歷支持 (P0355R7) 在 gcc libstdc++ 中尚不可用。 任何人都知道這是否正確或有指向此 ETA 的鏈接? 還是我調用 parse() 的方式有什么問題?
對於 std::put_time() 的錯誤 B:因為 std:put_time() 記錄為 c++11 感覺我在這里遺漏了一些愚蠢的東西。 還發現需要通過 c 的 time_t 和 tm 進行隱藏很奇怪。 有沒有更好的方法將 std::chrono::time_point 直接轉換為 std::string 而無需使用 c?
#include <chrono>
#include <string>
#include <sstream>
#include <iostream>
int main(int argc, char *argv[]) {
std::chrono::system_clock::time_point myDate;
//Create time point from string
//Ref: https://en.cppreference.com/w/cpp/chrono/parse
std::stringstream ss;
ss << "2020-05-24";
ss >> std::chrono::parse("%Y-%m-%e", myDate); //error A: ‘parse’ is not a member of ‘std::chrono’
//Write time point to string
//https://en.cppreference.com/w/cpp/io/manip/put_time
//http://cgi.cse.unsw.edu.au/~cs6771/cppreference/en/cpp/chrono/time_point.html
std::string dateString;
std::time_t dateTime = std::chrono::system_clock::to_time_t(myDate);
std::tm tm = *std::localtime(&dateTime);
dateString = std::put_time(&tm, "%Y-%m-%e"); //error B: ‘put_time’ is not a member of ‘std’
//Write out
std::cout << "date: " << dateString << "\n";
return 0;
}
C++20 <chrono>
仍在為 gcc 構建中。 我沒有看到任何公開的 ETA。
您的std::chrono::parse
看起來是正確的。 如果您願意使用C++20 <chrono>
的免費、開源、僅標頭預覽版,則可以通過添加#include "date/date.h"
並使用date::parse
來使其工作反而。
請注意,生成的myDate
將為 2020-05-24 00:00:00 UTC。
std::put_time
位於 header <iomanip>
並且是一個manipulator 。 添加 header 和<iostream>
后,您將像這樣使用它:
std::cout << "date: " << std::put_time(&tm, "%Y-%m-%e") << '\n';
如果您需要std::string
中的 output ,則必須首先將操縱器 stream 到std::stringstream
。
C++20 <chrono>
將為 C API 提供替代格式:
std::cout << "date: " << std::format("{%Y-%m-%e}", myDate) << '\n';
預覽庫還提供了一個稍微改變的格式字符串:
std::cout << "date: " << date::format("%Y-%m-%e", myDate) << '\n';
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.