std::time_point from and to std::string

std::time_point from and to std::string

本文关键字:std to string and point time from      更新时间:2023-10-16

我试图用 c++20 std::chrono 替换一些 boost::gregorian 代码,希望消除 boost 构建缺陷。 代码正在读取和写入json(使用nlohmann(,因此将日期与std::string之间的日期相互转换的能力至关重要。

在 Ubuntu 20.04 上使用 g++ 9.3.0。 2 个编译时错误,一个在 std::chrono::p arse(( 上,第二个在 std::p ut_time(( 上

对于 std::chrono::p arse(( 上的错误 A,我在这里看到日历支持 (P0355R7(,包括 chrono::p arse,在 gcc libstdc++ 中尚不可用。 有谁知道这是否正确或有指向 ETA 的链接?还是我调用 parse(( 的方式有问题?

对于 std::p ut_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住在标头<iomanip>中,是一个操纵者。 添加该标头并<iostream>后,您将像这样使用它:

std::cout << "date: " << std::put_time(&tm, "%Y-%m-%e") << 'n';

如果您需要std::string中的输出,则必须先将操纵器流式传输到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';