OLE日期到Posix_time的时间

时间:2011-03-09 13:00:14

标签: c++ datetime ole

最好的方法是什么,没有使用MS COM库将OLE日期时间格式转换为boost使用的posix_datetime?

OLE日期时间表示为浮点数。

1 个答案:

答案 0 :(得分:3)

你必须手动完成......我找不到其他任何方式......

boost::posix_time::ptime datetime_ole_to_posix(double ole_dt)
{
  static const boost::gregorian::date ole_zero(1899,12,30);

  boost::gregorian::days d(ole_dt);
  boost::posix_time::ptime pt(ole_zero + d);

  ole_dt -= d.days();
  ole_dt *= 24 * 60 * 60 * 1000;

  return pt + boost::posix_time::milliseconds(std::abs(ole_dt));
}

测试正确性:

void datetime_ole_to_posix_test()
{
  using boost::gregorian::date;
  using namespace boost::posix_time;

  /* http://msdn.microsoft.com/en-us/library/38wh24td.aspx */
  BOOST_ASSERT(datetime_ole_to_posix(-1.0) == ptime(date(1899,12,29)));
  BOOST_ASSERT(datetime_ole_to_posix(-1.25) == ptime(date(1899,12,29), hours(6)));
  BOOST_ASSERT(datetime_ole_to_posix(0.0) == ptime(date(1899,12,30)));
  BOOST_ASSERT(datetime_ole_to_posix(1.0) == ptime(date(1899,12,31)));
  BOOST_ASSERT(datetime_ole_to_posix(2.25) == ptime(date(1900,01,01), hours(6)));

  BOOST_ASSERT(datetime_ole_to_posix(2.0) == ptime(date(1900,01,01)));
  BOOST_ASSERT(datetime_ole_to_posix(5.0) == ptime(date(1900,01,04)));
  BOOST_ASSERT(datetime_ole_to_posix(5.25) == ptime(date(1900,01,04), hours(6)));
  BOOST_ASSERT(datetime_ole_to_posix(5.5) == ptime(date(1900,01,04), hours(12)));
  BOOST_ASSERT(datetime_ole_to_posix(5.875) == ptime(date(1900,01,04), hours(21)));
}