简体   繁体   English

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

[英]Convert tm structure to boost::local_time::local_date_time

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

Bit of a pain, but it seems like you have to go via posix_time::ptime: 有点痛苦,但似乎你必须经过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;

This will help you to convert tm structure into posix_time object. 将帮助您将tm结构转换为posix_time对象。 Look around for more conversions. 寻找更多转化。

#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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM