首页 > 解决方案 > 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。我有一个简单的输入,用户可以在其中定义输入的日期时间格式。

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

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

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

这是cppreference文档中的错误,这是 Visual Studio 实现中未完全实现的功能,还是(很可能)我只是错过了一些明显的东西?

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

标签: c++dateparsingc++20chrono

解决方案


据我所知,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


推荐阅读