【发布时间】:2011-01-20 21:09:57
【问题描述】:
我正在尝试将收到的日期时间转换为特定格式以插入 MySQL 数据库。该程序是用 C++ 编写的,以下解决方案有效,但我觉得它的效率非常低。
输入是:Mon Nov 08 17:41:23 +0000 2010
所需的输出格式为:YYYY-MM-DD HH:MM:SS
所以对于这个例子,输出将是:2010-11-08 17:41:23
我已经包含了代码的相关部分。
//class variable
std::map<std::string, std::string> monthMap;
void processor::initializeMonthMap(){
monthMap["Jan"] = "01";
monthMap["Feb"] = "02";
monthMap["Mar"] = "03";
monthMap["Apr"] = "04";
monthMap["May"] = "05";
monthMap["Jun"] = "06";
monthMap["June"] = "06";
monthMap["Jul"] = "07";
monthMap["July"] = "07";
monthMap["Aug"] = "08";
monthMap["Sept"] = "09";
monthMap["Sep"] = "09";
monthMap["Oct"] = "10";
monthMap["Nov"] = "11";
monthMap["Dec"] = "12";
}
inline std::string processor::convertDate(std::string input) {
//Format: Mon Nov 08 17:41:23 +0000 2010
//To get to YYYY-MM-DD HH:MM:SS
std::stringstream newString(input);
std::string temp1;
std::string temp2;
// Read Day in txt, discard
newString >> temp1;
//Read month, convert to number
newString >> temp1;
temp2 = "-" + monthMap[temp1] + "-";
//Read Day in number
newString >> temp1;
temp2.append(temp1 + " ");
//Read TimeStamp
newString >> temp1;
temp2.append(temp1);
//Discard UTM adjustment
newString >> temp1;
//Read year
newString >> temp1;
//Add year to beginning of input
temp1.append(temp2);
return temp1;
}
【问题讨论】:
-
您可以使用正则表达式(std::tr1 或 boost::regex)来获得干净的解决方案。如果您的格式是标准的,您也可以查看 Boost.Date_Time。
-
你测量过编译器优化代码的运行吗?您的代码看起来非常简单。你可以挤出更多,但这值得吗?像您这样干净、易于理解且相当高效的代码非常值得。 (如果您刚刚将 tempXXX 重命名为合理的名称……;)
-
总的来说,我同意@Peter。但是在这种情况下,使用日期/时间库,此代码基本上可以减少到两行:
get_date_from_string(..., format)后跟get_string_from_date(..., other_format)。这样会更清楚更简洁。
标签: c++ string datetime tokenize