【问题标题】:How do I create boost::posix_time::ptime objects from strings created using QDateTime ISODate format?如何从使用 QDateTime ISODate 格式创建的字符串创建 boost::posix_time::ptime 对象?
【发布时间】:2013-05-30 22:46:20
【问题描述】:

我正在使用我的新应用迁移旧应用数据库。旧应用使用 QT,新应用不使用。

我想将已存储在数据库中的日期转换为 boost::posix_time::ptime 对象。通过将 QDateTime 对象转换为 ISODate 格式的字符串,将日期存储在数据库中。

因此,源字符串具有以下格式:

YYYY-MM-DDTHH:MM:SSSZ

是否有一个简单的例程可用于从 QDateTime 字符串生成 ptime?我已经尝试过 posix_time::from_iso_string,但是由于日期中存在“-”分隔符而失败(并且可能“:”分隔符也是一个问题)。

【问题讨论】:

  • 您可能只需要编写自己的解析器。字符串都是这样严格格式化的吗?在这种情况下,如果你能忍受它,你可以使用类似 sscanf 的东西,或者只是从头开始编写一个简单的解析器。或使用提升正则表达式。 boost 精神可能是矫枉过正,会导致痛苦的编译时间,但在其他方面很好。
  • 或者只是去掉不需要的字符的字符串并使用 from_iso_string。
  • 你到底是怎么得到iso日期的?我可以在QDateTime 上找到toString 方法。

标签: c++ qt boost


【解决方案1】:

没有时区(Z 格式标志),这很容易。请参阅以下代码。

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

int main(int argc, char *argv[]) {
    const boost::posix_time::ptime time_with_ms = boost::date_time::parse_delimited_time<boost::posix_time::ptime>("2013-05-31T09:00:00.123", 'T');
    const boost::posix_time::ptime time_without_ms = boost::date_time::parse_delimited_time<boost::posix_time::ptime>("2013-05-31T09:00:00", 'T');
    std::cout << boost::posix_time::to_simple_string(time_with_ms) << std::endl;
    std::cout << boost::posix_time::to_simple_string(time_without_ms) << std::endl;
    return 0;
}

【讨论】:

    猜你喜欢
    • 2013-10-23
    • 1970-01-01
    • 2011-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多