从字符串创建 std::chrono::time_point

Create std::chrono::time_point from string

一个这样的

int
main()
{
    using namespace date;
    std::cout << std::chrono::system_clock::now() << '\n';
}

打印类似 2017-09-15 13:11:34.356648.

的内容

假设我的代码中有一个字符串文字 "2017-09-15 13:11:34.356648"

在 C++20 中从它创建 std::chrono::time_point 的正确方法是什么?

需要说明的是,C++20 中没有 namespace date。所以问题中的代码应该是这样的:

#include <chrono>
#include <iostream>

int
main()
{
    std::cout << std::chrono::system_clock::now() << '\n';
}

与此相反的是 std::chrono::parse,它对流进行操作。如果需要,您也可以使用 std::chrono::from_streamparse 是一个使语法更漂亮的流操纵器。

istringstream in{"2017-09-15 13:11:34.356648"};
system_clock::time_point tp;
in >> parse("%F %T", tp);

(为了避免冗长,我删除了命名空间)

使用的 locale 是构建 istringstream 时有效的全局语言环境。如果您更喜欢另一个 locale,请使用 imbue 成员函数来设置所需的 localelocale 只会影响此示例中的小数点字符。

%T 将读取输入 time_point 的任何精度(从微秒到纳秒随平台变化)。如果你想确保你可以解析纳秒,即使 system_clock::time_point 比那更粗糙,那么你可以解析成 sys_time<nanoseconds> 这是 time_point<system_clock, nanoseconds>.

的类型别名
sys_time<nanoseconds> tp;
in >> parse("%F %T", tp);

如果输入流的精度小于输入time_point,则没有问题。流中的内容将被读取,仅此而已。如果输入流的精度比输入 time_point 更精细,则解析会在 time_point 的精度处停止,并且流中剩余的数字将保持未解析状态。

Other strptime-like parsing flags are supported.