Tony The Lion
Tony The Lion

Reputation: 63320

OLE Date Time to Posix_time

what's the best way, without using MS COM libs to convert OLE date time format to a posix_datetime used by boost?

OLE date time is represented as a floating point number.

Upvotes: 1

Views: 1116

Answers (1)

Tony The Lion
Tony The Lion

Reputation: 63320

You have to do it manually... Just no other way I've found to do this...

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));
}

Tests for correctness:

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)));
}

Upvotes: 4

Related Questions