实现思路
- 成员变量:使用
std::tm
结构体来存储日期和时间信息。
- 构造函数:初始化
std::tm
结构体的成员变量。
- 格式化输出函数:使用
<ctime>
库中的strftime
函数将std::tm
结构体格式化为指定格式的字符串。
- 输入解析函数:使用
<regex>
库来解析输入的字符串,提取出日期和时间的各个部分,并填充到std::tm
结构体中。
- 异常处理:在解析函数中,如果输入字符串格式不正确,抛出
std::invalid_argument
异常。
- 性能优化:使用
<regex>
库的缓存机制来提高正则表达式匹配的性能。
类定义及关键成员函数实现
#include <iostream>
#include <string>
#include <ctime>
#include <regex>
class DateTimeFormatter {
private:
std::tm dateTime;
public:
// 构造函数
DateTimeFormatter(int year = 1970, int month = 1, int day = 1,
int hour = 0, int minute = 0, int second = 0) {
dateTime.tm_year = year - 1900;
dateTime.tm_mon = month - 1;
dateTime.tm_mday = day;
dateTime.tm_hour = hour;
dateTime.tm_min = minute;
dateTime.tm_sec = second;
}
// 格式化输出函数
std::string format() const {
char buffer[26];
std::strftime(buffer, 26, "%Y-%m-%d %H:%M:%S", &dateTime);
return std::string(buffer);
}
// 输入解析函数
void parse(const std::string& input) {
static const std::regex dateTimeRegex("(\\d{4})-(\\d{2})-(\\d{2}) (\\d{2}):(\\d{2}):(\\d{2})");
std::smatch match;
if (!std::regex_search(input, match, dateTimeRegex)) {
throw std::invalid_argument("Invalid date time format");
}
dateTime.tm_year = std::stoi(match[1]) - 1900;
dateTime.tm_mon = std::stoi(match[2]) - 1;
dateTime.tm_mday = std::stoi(match[3]);
dateTime.tm_hour = std::stoi(match[4]);
dateTime.tm_min = std::stoi(match[5]);
dateTime.tm_sec = std::stoi(match[6]);
}
};
示例使用
int main() {
try {
DateTimeFormatter formatter;
formatter.parse("2023-10-05 14:30:00");
std::cout << "Formatted: " << formatter.format() << std::endl;
DateTimeFormatter formatter2(2023, 10, 6, 15, 45, 30);
std::cout << "Formatted 2: " << formatter2.format() << std::endl;
} catch (const std::exception& e) {
std::cerr << "Exception: " << e.what() << std::endl;
}
return 0;
}