myk*_*myk 4 c++ c++-chrono c++20
我尝试使用 c++20 std::chrono 替换一些 boost::gregorian 代码,希望消除 boost 构建依赖性。代码正在读取和写入 json(使用 nlohmann),因此将日期与 std::string 相互转换的能力至关重要。
\n\n在 Ubuntu 20.04 上使用 g++ 9.3.0。2 个编译时错误,第一个错误发生在 std::chrono::parse() 上,第二个错误发生在 std::put_time() 上
\n\n对于 std::chrono::parse() 上的错误 A,我在这里看到日历支持 (P0355R7)(包括 chrono::parse)在 gcc libstdc++ 中尚不可用。有人知道这是否正确或者有 ETA 的链接吗?或者我调用 parse() 的方式有问题吗?
\n\n对于 std::put_time() 的错误 B:因为 std::put_time() 被记录为 c++11 感觉我在这里错过了一些愚蠢的东西。还觉得需要通过 c\'s time_t 和 tm 进行隐藏很奇怪。有没有更好的方法将 std::chrono::time_point 直接转换为 std::string 而无需求助于 c?
\n\n#include <chrono>\n#include <string>\n#include <sstream>\n#include <iostream>\n\nint main(int argc, char *argv[]) {\n std::chrono::system_clock::time_point myDate;\n\n //Create time point from string\n //Ref: https://en.cppreference.com/w/cpp/chrono/parse\n std::stringstream ss;\n ss << "2020-05-24";\n ss >> std::chrono::parse("%Y-%m-%e", myDate); //error A: \xe2\x80\x98parse\xe2\x80\x99 is not a member of \xe2\x80\x98std::chrono\xe2\x80\x99\n\n //Write time point to string\n //https://en.cppreference.com/w/cpp/io/manip/put_time\n //http://cgi.cse.unsw.edu.au/~cs6771/cppreference/en/cpp/chrono/time_point.html\n std::string dateString;\n std::time_t dateTime = std::chrono::system_clock::to_time_t(myDate);\n std::tm tm = *std::localtime(&dateTime);\n dateString = std::put_time(&tm, "%Y-%m-%e"); //error B: \xe2\x80\x98put_time\xe2\x80\x99 is not a member of \xe2\x80\x98std\xe2\x80\x99\n\n //Write out\n std::cout << "date: " << dateString << "\\n";\n\n return 0;\n}\nRun Code Online (Sandbox Code Playgroud)\n
gcc 的C++20<chrono>仍在构建中。我没有看到任何公开的预计到达时间。
您的语法std::chrono::parse看起来正确。如果您愿意使用免费、开源、仅包含头文件的 C++20 预览版<chrono>#include "date/date.h",那么您可以通过添加和使用来使其正常工作date::parse。
请注意,结果myDate将为 2020-05-24 00:00:00 UTC。
std::put_time住在头部<iomanip>,是一个操纵者。添加该标头后,<iostream>您将像这样使用它:
std::cout << "date: " << std::put_time(&tm, "%Y-%m-%e") << '\n';
Run Code Online (Sandbox Code Playgroud)
如果您需要 a 中的输出std::string,则必须将操纵器流式传输到 astd::stringstream首先将操纵器流式传输到 a 。
C++20<chrono>将提供 C API 的替代方案用于格式化:
std::cout << "date: " << std::format("{%Y-%m-%e}", myDate) << '\n';
Run Code Online (Sandbox Code Playgroud)
预览库还为此提供了稍微改变的格式字符串:
std::cout << "date: " << date::format("%Y-%m-%e", myDate) << '\n';
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3100 次 |
| 最近记录: |