将tm结构转换为boost :: local_time :: local_date_time

时间:2009-07-31 11:58:51

标签: c++ boost

如何从boost::local_time::local_date_time时间结构创建tm对象?

3 个答案:

答案 0 :(得分:6)

有点痛苦,但似乎你必须经过posix_time :: ptime:

using namespace boost;
time_t rawtime;
time(&rawtime);
struct tm* timeinfo = localtime(&rawtime);
posix_time::ptime my_ptime = posix_time::ptime_from_tm(*timeinfo);
local_time::time_zone_ptr zone(new local_time::posix_time_zone("GMT"));
local_time::local_date_time my_ldt(my_ptime, zone);
std::cout << "local_date_time: " << my_ldt << std::endl;

答案 1 :(得分:1)

This 将帮助您将tm结构转换为posix_time对象。四处寻找更多转换。

答案 2 :(得分:0)

#define MSEC_TICKS_PER_SECOND 1000
boost::local_time::local_date_time ConvertTimeZone(
    const std::tm &from_tm,
    const int16_t &from_milliseconds,
    const boost::local_time::time_zone_ptr &from_tz,
    const boost::local_time::time_zone_ptr &to_tz) {
  using boost::gregorian::date;
  using boost::posix_time::time_duration;
  using boost::local_time::local_date_time;
  local_date_time from_ldt(
      date(from_tm.tm_year + 1900,
           from_tm.tm_mon + 1,
           from_tm.tm_mday),
      time_duration(from_tm.tm_hour,
                    from_tm.tm_min,
                    from_tm.tm_sec,
                    time_duration::ticks_per_second() / MSEC_TICKS_PER_SECOND *
                    from_milliseconds),
      from_tz,
      boost::local_time::local_date_time::NOT_DATE_TIME_ON_ERROR);
  return from_ldt.local_time_in(to_tz);
}
#undef MSEC_TICKS_PER_SECOND