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

时间:2010-06-07 01:38:52

标签: c++ boost datetime

目前我正在尝试读取格式化的时间字符串并从中创建持续时间。我目前正在尝试使用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

2 个答案:

答案 0 :(得分:5)

从文档中看起来您可能想尝试使用流操作符(operator<<operator>>);错误条件在Date Time Input/Output描述。

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

修改 如果不是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;
    }
}

答案 1 :(得分:2)

使用流操作符。

time_duration td;
if (std::cin >> td)
{
   // it's valid
}
else
{
   // it isn't valid
}