【发布时间】:2016-02-20 06:44:09
【问题描述】:
我正在尝试将一个很长的 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 字符串。如何实际获得正确的日期时间字符串,在这种情况下为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();
}
【问题讨论】:
-
这是否会在手册中执行“from_unixtime” - dev.mysql.com/doc/refman/5.5/en/…
-
嗯,是的,但我实际上必须将 DATETIME 字符串插入 MySQL。时间戳值是从服务中获取的,我需要将其转换为 DATETIME 字符串,以便将其与时间戳一起插入表中。到目前为止,我还没有遇到在插入期间直接将时间戳转换为 DATETIME 的方法,所以我使用的是我上面发布的方法。感谢您的回复。
-
日期时间不是字符串。 MySql 中的大量转换 - dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html
-
是的,但它需要在一个字符串中,该字符串将添加到完整的插入查询字符串中,整个查询将被发送到 MySQL
-
不,它没有。绑定变量(防止SQL注入一开始)
标签: c++ mysql datetime unix boost