代码之家  ›  专栏  ›  技术社区  ›  stefanB

增压日期添加一天,非标准GMT字符串

  •  1
  • stefanB  · 技术社区  · 17 年前

    在C++中,以这种格式向日期添加一天的最简单方法是什么:

    可能使用Boost 1.36- Boost::date , Boost::posix_date 或任何其他刺激或 std

    到目前为止,我提出了:

    • boost::gregorian::date ,日期格式如下:

      "2009-06-29 05:57:43"

      "20090629-05:57:43"

    • 加上一天(提振) date_duration (材料)

    • to_simple_string

    有没有更简单/更漂亮的方法?

    我关注的是运行时效率。

    上述步骤的示例代码:

    using namespace boost::gregorian;
    string orig("20090629-05:57:43");
    string dday(orig.substr(0,8));
    string dtime(orig.substr(8));
    
    date d(from_undelimited_string(dday));
    date_duration dd(1);
    d += dd;
    string result(to_iso_string(d) + dtime);
    

    结果:

    20090630-05:57:43
    
    1 回复  |  直到 17 年前
        1
  •  1
  •   Head Geek    17 年前

    #include <iostream>
    #include <sstream>
    #include <locale>
    #include <boost/date_time.hpp>
    
    using namespace boost::local_time;
    
    int main() {
        std::stringstream ss;
        local_time_facet* output_facet = new local_time_facet();
        local_time_input_facet* input_facet = new local_time_input_facet();
        ss.imbue(std::locale(std::locale::classic(), output_facet));
        ss.imbue(std::locale(ss.getloc(), input_facet));
    
        local_date_time ldt(not_a_date_time);
    
        input_facet->format("%Y%m%d-%H:%M:%S");
        ss.str("20090629-05:57:43");
        ss >> ldt;
    
        output_facet->format("%Y%m%d-%H:%M:%S");
        ss.str(std::string());
        ss << ldt;
    
        std::cout << ss.str() << std::endl;
    }
    

    不过,这要长得多,而且可能更难理解。我还没有试图证明这一点,但我怀疑这样做的运行效率大致相同。

    推荐文章