如何解析日期字符串到一个c ++ 11 std :: chrono time_point或类似? [英] How to parse a date string into a c++11 std::chrono time_point or similar?

查看:794
本文介绍了如何解析日期字符串到一个c ++ 11 std :: chrono time_point或类似?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下格式的历史日期字符串:

Consider a historic date string of format:

Thu Jan 9 12:35:34 2014

我想将这样的字符串解析为某种C ++日期表示,

I want to parse such a string into some kind of C++ date representation, then calculate the amount of time that has passed since then.

在这段时间内,我需要访问秒,分,小时和天的数字。

From the resulting duration I need access to the numbers of seconds, minutes, hours and days.

这可以用新的C ++ 11 std :: chrono 命名空间来完成吗?

Can this be done with the new C++11 std::chrono namespace? If not, how should I go about this today?

我使用g ++ - 4.8.1虽然大概一个答案应该只针对C ++ 11规范。 / p>

I'm using g++-4.8.1 though presumably an answer should just target the C++11 spec.

推荐答案

std::tm tm = {};
std::stringstream ss("Jan 9 2014 12:35:34");
ss >> std::get_time(&tm, "%b %d %Y %H:%M:%S");
auto tp = std::chrono::system_clock::from_time_t(std::mktime(&tm));

因为GCC不实现 std :: get_time

Because GCC doesn't implement std::get_time you should also be able to write:

std::tm tm = {};
strptime("Thu Jan 9 2014 12:35:34", "%a %b %d %Y %H:%M:%S", &tm);
auto tp = std::chrono::system_clock::from_time_t(std::mktime(&tm));

这篇关于如何解析日期字符串到一个c ++ 11 std :: chrono time_point或类似?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆