使用 spirit 将日期时间字符串解析为time_t值

parse a date-time string into a time_t value with spirit

本文关键字:time spirit 日期 时间 字符串 使用      更新时间:2023-10-16

我需要使用boost::spirit将像2012-12-21 12:10:35这样的日期时间字符串解析为time_t值。 这是我的代码片段:

tc_     =   lexeme[int_[phx::ref(tm_.tm_year)=(_1-1900)]>>'-'
>>int_[phx::ref(tm_.tm_mon)=(_1-1)]>>'-'
>>int_[phx::ref(tm_.tm_mday)=_1]>>+space
>>int_[phx::ref(tm_.tm_hour)=_1]>>':'
>>int_[phx::ref(tm_.tm_min)=_1]>>':'
>>int_[phx::ref(tm_.tm_sec)=_1]]    [_val = (long)mktime(&tm_)];

其中tc_是类型为qi::rule<Iterator, long(), Skipper>qi规则,tm_是类型为struct tm的成员变量。

代码可以编译,但不起作用。 看来mktime()根本没有被叫到。 我做错了什么?

你可以在 C++ 11 vi 正则表达式中做到这一点。 如果您的编译器足够新,这将是可移植和标准的。

#include <iostream>
#include <string>
#include <regex>
using namespace std;
int main()
{
std::regex txt_regex("([0-9]{4})[-]([0-9]{2})[-]([0-9]{2})[ ]([0-9]{2})([:])([0-9]{2})([:])([0-9]{2})");//  
string strTmp;
strTmp="2010-12-15 15:25:46";
std::smatch match;
std::regex_search( strTmp, match, txt_regex );
if(regex_match(strTmp,txt_regex))
cout<<"Ok"<<endl;
else
{
cout<<"Invalid input"<<endl;
return 0;
}
if ( match.empty() )
{
std::cout << "...no more matches" << std::endl;
return 0;
}
for ( auto x : match )
{
std::cout << "found: " << x << std::endl;
}
string str = match.suffix().str();
cout <<str <<std::endl;
return 0; 
}

有了这个,您可以显示要显示的字符串的不同部分,然后填充结构。

希望它有所帮助,并像往常一样开放评论(如果某些内容不清楚或不完整)。