加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

比较日期c(使用提升)

发布时间:2020-12-16 07:31:44 所属栏目:百科 来源:网络整理
导读:我需要能够转换和比较c中的日期.我发现boost库非常适合我的需求,但我无法让它正常工作: // include headers... using namespace boost::posix_time; using namespace boost::gregorian;ptime p1(second_clock::universal_time());p1 -= weeks(5); // Subtra
我需要能够转换和比较c中的日期.我发现boost库非常适合我的需求,但我无法让它正常工作:

// include headers... 

using namespace boost::posix_time; 
using namespace boost::gregorian;

ptime p1(second_clock::universal_time());

p1 -= weeks(5); // Subtract 5 weeks from p1 using boost...

std::string old_date("2011-11-19"); // format:YYYY-MM-DD

std:stringstream ss(old_date);

ptime p2;

p2 << ss;

if(p1 <= p2){
    // this should not happen in this case (yet it does!) p1 > p2!!
}

基本上我希望能够减去本地日期的周(或月),然后将结果与以YYYY-MM-DD格式作为字符串给出的日期进行比较…

解决方法

您的区域设置可能未设置为以YYYY-MM-DD格式识别日期.尝试设置输入构面格式,如 Format Strings示例中所示.

这是一个示例,显示如何将字符串流的输入和输出格式设置为“ISO扩展”:

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

int main()
{
    using namespace boost::gregorian;
    using namespace boost::posix_time;
    using namespace std;

    stringstream ss;

    /****** format strings ******/
    time_facet* output_facet = new time_facet();
    time_input_facet* input_facet = new time_input_facet();
    ss.imbue(locale(ss.getloc(),output_facet));
    ss.imbue(locale(ss.getloc(),input_facet));
    output_facet->format(time_facet::iso_time_format_extended_specifier);
    input_facet->format(time_input_facet::iso_time_format_extended_specifier);
    ptime t(second_clock::local_time());
    ss << t;
    cout << ss.str() << endl; // 2012-08-03 23:46:38
    ss.str("2000-01-31 12:34:56");
    ss >> t;
    assert(t.date().year() == 2000);
    assert(t.date().month() == 1);
    assert(t.date().day() == 31);
    assert(t.time_of_day().hours() == 12);
    assert(t.time_of_day().minutes() == 34);
    assert(t.time_of_day().seconds() == 56);
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读