2017-09-25 40 views
2

我想从boost :: C++的std :: string日期时间中仅获得小时和分钟。 我有下面的代码。从std :: string获取小时和分钟boost C++

std::string d_time = std::string("2017-09-25 12:23:10"); 

我可以令牌化上面的字符串得到它,但没有任何标准提升功能,这将使由“D_TIME”只有小时和分钟?

在此先感谢。

+0

有些系统有一个名为'strptime'的函数,它可以将时间和日期字符串转换为'struct tm',从中可以获得所需的信息。你可以检查。 –

+1

您也可以将['std :: get_time'](http://en.cppreference.com/w/cpp/io/manip/get_time)与['std :: istringstream'](http:///en.cppreference.com/w/cpp/io/basic_istringstream)。 –

+0

但是struct tm在windows下不可用吗? – Neel

回答

2

功能std::get_timestd::put_time可以帮助你。

这些函数与stream对象一起使用,因此如果要处理字符串,则可以使用stringstream

std::istringstream time_stream{d_time}; // Construct a stream from string 
std::tm time; // Time structure 
time_stream >> std::get_time(&time, "%Y-%m-%d %H:%M:%S"); // Fill time struct 

一旦你正确初始化std::tm结构,可以提取所需要的信息(小时和分钟)。

Here一个现场演示。

请注意,这些功能是标准 C++ 11的一部分。

+2

还要注意[gcc 4.x](https://wandbox.org/permlink/vEYlLpND6ANIlSk7)即使在C++ 11模式下也没有实现。你至少需要5.x – sehe

+0

在这里,如果我们使用旧版本的gcc <5,那么“std :: get_time”和“std :: put_time”不被支持? – Neel

+0

@Neel看到我的[answer](https:// stackoverflow。com/a/46401318/85371) – sehe

2

如果您使用一个版本的编译器/标准库的不正确实施put_time/GET_TIME机械手,这里的一小块代码使用Boost的DateTime

Live On Wandbox

#include <boost/date_time/posix_time/posix_time.hpp> 

using boost::posix_time::time_from_string; 

int main() { 
    auto time = time_from_string("2017-09-25 12:23:10").time_of_day();; 

    int hours = time.hours(); 
    int minutes = time.minutes(); 

    std::cout << "hours: " << hours << " minutes:" << minutes << "\n"; 
} 
+0

它给编译错误说“class boost :: posix_time :: ptime'没有名为'hours'的成员” – Neel

+0

有一个现场演示。仔细观察(你忘了'time_of_day()'调用) – sehe