使用yaml-cpp解析YAML !!时间戳(日期时间)

时间:2013-05-09 21:08:00

标签: c++ yaml yaml-cpp

我正在使用yaml-cpp惊人的库来解析YAML文件,我需要解析!!时间戳类型的标量。例如:

- timeSpec:
    startTime: 2013-05-15T02:59:43.138Z
    endTime: 2013-05-23T02:59:43.138Z

1 - 我怎么能这样做?我应该将它解析为std :: string并自己处理日期时间的解析吗?我是否需要导入一些boost库,以便数据类型转换直截了当?

2 - 一般来说,图书馆支持YAML basic data types是什么?

2 个答案:

答案 0 :(得分:2)

您必须自己解析日期时间。如果您有一些结构DateTime,作为骨架,您可以写:

namespace YAML {
   template<>
   struct convert<DateTime> {
      static Node encode(const DateTime& rhs) {
         std::string str = YourCodeToConvertToAString(rhs);
         return Node(str);
      }

      static bool decode(const Node& node, DateTime& rhs) {
         if(!node.IsScalar())
            return false;

         std::string str = node.as<std::string>();
         // Fill in the DateTime struct.
         return true;
      }
   };
}

如果您可以找到一个库(也许是提升)来做到这一点,那会更容易,但是日期时间的YAML格式可能不像其他库所期望的那样。

通常,yaml-cpp不支持任何自动类型检测。

答案 1 :(得分:1)

我知道这有点晚了,但我遇到了同样的事情。对我来说,最快捷,最简单的解决方案是在YAML文档中创建日期字符串,并使用boost将字符串转换为posix时间类型:

boost::posix_time::from_iso_string(node[0]["timeSpec"]["startTime"].as<std::string>())