【问题标题】:boost date parse 29FEB提升日期解析 29FEB
【发布时间】:2016-03-25 22:33:52
【问题描述】:

日期时间解析存在一些问题,我不知道有什么好的解决方法。

考虑以下代码:

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

namespace dt = boost::gregorian;

dt::date parse_date(const std::string& msg, const std::string& format)
{
   std::stringstream s(msg);
   dt::date_input_facet * f = new dt::date_input_facet();
   if (format.empty())
   {
      f->set_iso_format();
   }
   else
   {
      f->format(format.c_str());
   }
   std::locale l(std::locale(), f);
   s.imbue(l);
   dt::date result;
   s >> result;
   return result;
}

int main()
{
    const std::string v = "0229";
    auto p = parse_date(v, "%m%d");
    std::cout << p << std::endl;
}

Live example

问题是,日期时间解析器中的默认年份是1400,这不是闰年,所以今年没有 2 月 29 日。主要问题当然是为什么 1400 是默认年份而不是闰年,无论如何我需要一些好的解决方法,有什么想法吗?

【问题讨论】:

    标签: c++ boost boost-date-time


    【解决方案1】:

    我认为“为什么”的问题并不是特别相关¹。这就是它的工作方式。关键是你知道是什么阻止你解析它。

    我只是做简单的事情,下面,或者just write a tiny spirit parser (int_parser&lt;unsigned char, 10, 2, 2&gt; twice) 并直接构造一个ptime)。

    Live On Coliru

    #include <iostream>
    #include <string>
    #include <boost/date_time/gregorian/gregorian.hpp>
    
    namespace dt = boost::gregorian;
    
    dt::date parse_date_mmdd(const std::string &msg) {
        std::stringstream s("2000" + msg);
        dt::date_input_facet *f = new dt::date_input_facet();
        f->format("%Y%m%d");
    
        std::locale l(std::locale(), f);
        s.imbue(l);
        dt::date result;
        s >> result;
    
        return result;
    }
    
    int main() {
        const std::string v = "0229";
        auto p = parse_date_mmdd(v);
        std::cout << p << std::endl;
    }
    

    打印

    2000-Feb-29
    

    ¹ 答案可能集中在 “没有与 DayOfYear 关联的数据类型” 作为 DayOfMonth 元组(在日期处理库中没有用处)。所以你总是必须决定一个上下文年份。就像您总是必须决定在哪个时区解释 posix 时间。甚至要使用哪种日历模型。

    【讨论】:

    • 有一个 partial_date 但遗憾的是它不尊重他使用的格式字符串。如果“2902”而不是“0229”可以工作,他可以​​使用this
    • 很好的发现,@cv_and_he。我想知道partial_date 对其他任务有多大用处(有一天会看看)。这里是 the X3 version 以确保完整性
    • 有趣。当然,我有关于添加年份的想法,但我不喜欢这种方式,但可能是最好的。这是非常有趣的解决方案,使用 partial_date。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-08
    • 2023-03-28
    • 2017-04-24
    • 2012-12-26
    • 1970-01-01
    相关资源
    最近更新 更多