将时间字符串转换为持续时间

rad*_*man 1 c++ datetime boost

目前我正在尝试读取格式化的时间字符串并从中创建持续时间.我目前正在尝试使用boost date_time time_duration类来读取和存储该值.

boost date_time提供了一种方法time_duration duration_from_string(std::string),允许从时间字符串创建time_duration,并接受适当格式化的字符串("[-]h[h][:mm][:ss][.fff]".).

现在,如果使用格式正确的时间字符串,此方法可以正常工作 但是,如果您提交的内容无效,例如"ham_sandwich"或"100",那么您将返回无效的time_duration.特别是如果您尝试将其传递给标准输出流,则会发生断言.

我的问题是:有谁知道如何测试boost time_duration的有效性?如果没有,你能建议另一种读取时间段并从中获取持续时间的方法吗?

注意:我尝试过time_duration提供的明显的测试方法; is_not_a_date_time(),is_special()等他们不接,有一个问题.

使用boost 1.38.0

Sam*_*eld 5

从文档中看起来您可能想尝试使用流运算符(operator<<,operator>>); 日期时间输入/输出中描述了错误条件.

或者,我想你可以在传入之前验证字符串.右边,看起来不像特定方法有任何错误处理.

编辑: 我不确定如果不是Brian的回答,我会考虑检查这样的返回值,但是为了完整性,这是一个以字符串作为输入的完整示例.您可以检查返回值或让它抛出异常(我相信您想要捕获std::ios_base_failure):

#include <iostream>
#include <sstream>
#include <string>
#include <boost/date_time/posix_time/posix_time.hpp>

using namespace std;
using namespace boost::posix_time;

int main(int argc, char **argv) {
    if (argc < 2) {
        cout << "Usage: " << argv[0] << " TIME_DURATION" << endl;
        return 2;
    }

    // No exception
    stringstream ss_noexcept(argv[1]);
    time_duration td1;
    if (ss_noexcept >> td1) {
        cout << "Valid time duration: " << td1 << endl;
    } else {
        cout << "Invalid time duration." << endl;
    }

    // Throws exception
    stringstream ss2;
    time_duration td2;
    ss2.exceptions(ios_base::failbit);
    ss2.str(argv[1]);
    try {
        ss2 >> td2;
        cout << "Time duration: " << td2 << endl;
    } catch (ios_base::failure e) {
        cout << "Invalid time duration (exception caught). what():\n"
                << e.what() << endl;
    }
}
Run Code Online (Sandbox Code Playgroud)