std::chrono::from_stream可以以微秒精度将字符串转换为time_point吗?

TLDR :

std::chrono::sys_time<std::chrono::microseconds> tTimePoint;
std::istringstream stream("2020-09-16 22:00:00.123456");

std::chrono::from_stream(stream, "%Y-%m-%d %H:%M:%S", tTimePoint);

我希望上面的代码解析.123456为微秒。但是,运行时tTimePoint只包含日期和时间,不包括亚秒。

更长

我在Windows 10上使用带有cpplatest标志的Visual Studio 2019。我有一个简单的输入,用户可以在其中定义输入的日期时间格式。

字符串可以看起来像2020-09-16T22:00:00.12345616.09.2020 22:00:00.123456或任何其他有效的日期时间格式,只要有一种方法可以使用std::chrono::from_stream的cppreference 中列出的限定符来描述它。

根据参考资料和我以前的经验std::format()(使用相同的格式),我假设它%S也解析亚秒。

我也试过,std::chrono::parse但这并没有说明%S会解析小数点后的亚秒。我尝试了各种不同的格式和日期时间格式,以确保此问题不会仅由于某些不规则的日期时间格式而发生。

这是cppreference文档中的错误,这是 Visual Studio 实现中未完全实现的功能,还是(很可能)我只是简单地遗漏了一些明显的内容?

感谢您为我提供的任何帮助!

回答

据我所知,VS2019 在使用时存在缺陷,from_stream并且time_point应该使用亚秒。VS2019 库中有一个地方应该处理它 - 但它永远不会进入这种情况。

幸运的是,如果您使用 aduration而不是 a time_point,它起作用,因此您可以解决这个问题:

#include <chrono>
#include <sstream>
#include <iostream>

int main() {
    std::istringstream stream("2020-09-16 22:00:00.123456");

    std::chrono::sys_time<std::chrono::microseconds> tTimePoint;

    // extract all but the second:  
    std::chrono::from_stream(stream, "%Y-%m-%d %H:%M:", tTimePoint);

    std::chrono::microseconds micros;

    // extract the second:
    std::chrono::from_stream(stream, "%S", micros);

    // add the duration to the time_point
    tTimePoint += micros;

    std::cout << tTimePoint << 'n';
}

错误报告- 当前状态:已修复:Visual Studio 2022 版本 17.0 预览版 3


以上是std::chrono::from_stream可以以微秒精度将字符串转换为time_point吗?的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>