如何从C ++中的字符串中解析日期/时间

时间:2013-05-28 14:32:27

标签: c++ datetime boost string-conversion boost-date-time

如何将带有模板"%d.%m.%Y %H:%M:%S"的字符串(例如, 28.05.2013 17:42:00 )转换为boost::posix_time::ptime或类似内容?

以下是我的非工作代码。

boost::posix_time::ptime stringToDateTime(const std::string &text) {
  const std::locale fct
  (   std::locale::classic()
  ,   new boost::gregorian::date_input_facet("%d.%m.%Y %H:%M:%S")
  );
  std::istringstream is(text);
  is.imbue(fct);
  boost::posix_time::ptime date;
  is >> date;
  return date;
}

2 个答案:

答案 0 :(得分:0)

有一种丑陋的方式我不接受

boost::posix_time::ptime stringToDateTime(const std::string &text) {
  return boost::posix_time::time_from_string
  (   text.substr(6, 4) // year
  +   "-"
  +   text.substr(3, 2) // month
  +   "-"
  +   text.substr(0, 2) // day
  +   text.substr(10, 9) // hour,min,sec
  );
}

答案 1 :(得分:0)

boost::posix_time::ptime stringToDateTime(const std::string &text) {
  const std::locale fct
  (   std::locale::classic()
  ,   new boost::posix_time::time_input_facet("%d.%m.%Y %H:%M:%S")
  );           //^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - that was an error
  std::istringstream is(text);
  is.imbue(fct);
  boost::posix_time::ptime date;
  is >> date;
  return date;
}