繁体   English   中英

C ++ Boost将UNIX时间戳转换为与MySQL兼容的DATETIME字符串

[英]C++ Boost convert UNIX Timestamp to MySQL compatible DATETIME String

我正在尝试将长的UNIX时间戳转换为需要以这种格式存储在MySQL中的日期时间字符串,该格式为2016-02-01 03:15:10

这是我到目前为止所拥有的。 它在时间提取部分不起作用。 我找不到可以直接使用boost :: posix_time :: ptime对象的boost :: posix_time :: time_duration的构造函数。 所以我试图包括一个解决方法。 但这在hours()部分不起作用。

static inline std::string getDateTime(long timestamp) {
      std::stringstream date_str;
      boost::posix_time::ptime pt_1 = boost::posix_time::from_time_t(timestamp);

      /* workaround to somehow get a time_duration object constructed */
      boost::posix_time::ptime pt_temp = boost::posix_time::from_time_t(0);

      boost::gregorian::date d = pt_1.date();

      boost::posix_time::time_duration td = pt_1 - pt_temp;

      /* construct the Date Time string */
      date_str << d.year() << "-" << std::setw(2) << std::setfill('0') << d.month().as_number() << "-" << std::setw(2) << std::setfill('0') << d.day() << " "
               << td.hours() << ":" << td.minutes() << ":" << td.seconds();

      return date_str.str();
    }

使用时间戳输入(例如1455892259我从函数中将此2016-02-19 404414:30:59作为DateTime字符串获取。 如何实际获取正确的Date Time字符串(在这种情况下为2016-02-19 14:30:59 为此必须使用Boost。

更新

这是使用下面的Jarra McIntyre提供的答案重写的最终工作功能。

static inline std::string getDateTime(long timestamp) {
      std::stringstream date_str;
      boost::posix_time::ptime pt_1 = boost::posix_time::from_time_t(timestamp);

      boost::gregorian::date d = pt_1.date();

      auto td = pt_1.time_of_day();

      /* construct the Date Time string */
      date_str << d.year() << "-" << std::setw(2) << std::setfill('0') << d.month().as_number() << "-" << std::setw(2) << std::setfill('0') << d.day() << " "
               << td.hours() << ":" << td.minutes() << ":" << td.seconds();

      return date_str.str();
    }

采用

auto td = pt_1.time_of_day();

不需要解决方法来获取一天中的时间。 您的问题中显示的小时数可能是1970-01-01 00:00和2016-02-19 14:00之间的小时数。 为了使time_duration工作,您必须在同一天构造一个ptime,而不是在unix时间0上。

暂无
暂无

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

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