Skip to content

Instantly share code, notes, and snippets.

@coolxv
Last active June 6, 2024 14:24
Show Gist options
  • Save coolxv/47d882c840cfd4432008c6dd9eaf13a8 to your computer and use it in GitHub Desktop.
Save coolxv/47d882c840cfd4432008c6dd9eaf13a8 to your computer and use it in GitHub Desktop.
convert 6-Jun-2024 time format to 20240606 time format
#include <iostream>
#include <string>
#include <sstream>
#include <iomanip>
#include <ctime>
#include <map>
// 函数:将月份缩写转换为数字
int monthToNumber(const std::string& month) {
static std::map<std::string, int> monthMap = {
{"Jan", 1}, {"Feb", 2}, {"Mar", 3},
{"Apr", 4}, {"May", 5}, {"Jun", 6},
{"Jul", 7}, {"Aug", 8}, {"Sep", 9},
{"Oct", 10}, {"Nov", 11}, {"Dec", 12}
};
return monthMap[month];
}
// 函数:将6-Jun-2024格式转换为20240606格式
std::string convertDateFormat(const std::string& date) {
std::istringstream iss(date);
std::string dayStr, monthStr, yearStr;
std::getline(iss, dayStr, '-');
std::getline(iss, monthStr, '-');
std::getline(iss, yearStr, '-');
int day = std::stoi(dayStr);
int month = monthToNumber(monthStr);
int year = std::stoi(yearStr);
std::tm timeStruct = {};
timeStruct.tm_year = year - 1900; // tm_year是从1900年开始计算的
timeStruct.tm_mon = month - 1; // tm_mon是从0开始的,所以要减1
timeStruct.tm_mday = day;
char buffer[9]; // 8字符+1终止符
std::strftime(buffer, sizeof(buffer), "%Y%m%d", &timeStruct);
return std::string(buffer);
}
int main() {
std::string date = "6-Jun-2024";
std::string formattedDate = convertDateFormat(date);
std::cout << "Converted Date: " << formattedDate << std::endl;
return 0;
}
#include <iostream>
#include <string>
#include <sstream>
#include <iomanip>
#include <map>
// 函数:将月份缩写转换为数字
int monthToNumber(const std::string& month) {
static std::map<std::string, int> monthMap = {
{"Jan", 1}, {"Feb", 2}, {"Mar", 3},
{"Apr", 4}, {"May", 5}, {"Jun", 6},
{"Jul", 7}, {"Aug", 8}, {"Sep", 9},
{"Oct", 10}, {"Nov", 11}, {"Dec", 12}
};
return monthMap[month];
}
// 函数:将6-Jun-2024格式转换为20240606格式
std::string convertDateFormat(const std::string& date) {
std::istringstream iss(date);
std::string dayStr, monthStr, yearStr;
std::getline(iss, dayStr, '-');
std::getline(iss, monthStr, '-');
std::getline(iss, yearStr, '-');
int day = std::stoi(dayStr);
int month = monthToNumber(monthStr);
int year = std::stoi(yearStr);
std::ostringstream oss;
oss << year << std::setw(2) << std::setfill('0') << month << std::setw(2) << std::setfill('0') << day;
return oss.str();
}
int main() {
std::string date = "6-Jun-2024";
std::string formattedDate = convertDateFormat(date);
std::cout << "Converted Date: " << formattedDate << std::endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment