C/C++ let DATE format to “YYYY-MM-DD”
code:
#include <iostream>
#include <string>class compileDate {// 静态函数,用来格式化并返回编译日期
static std::string formatCompileDate() {// 编译时的日期,格式为 "MMM DD YYYY"const std::string date = __DATE__;// 定义月份的映射,使用数组而非std::mapstruct MonthMap {const char* short_name;const char* num;};static const MonthMap months[] = {{"Jan", "01"}, {"Feb", "02"}, {"Mar", "03"}, {"Apr", "04"},{"May", "05"}, {"Jun", "06"}, {"Jul", "07"}, {"Aug", "08"},{"Sep", "09"}, {"Oct", "10"}, {"Nov", "11"}, {"Dec", "12"}};// 解析 `__DATE__`std::string month = date.substr(0, 3); // 月份的前三个字母std::string day = date.substr(4, 2); // 日期std::string year = date.substr(7, 4); // 年份// 移除日期前的空格if (day[0] == ' ') {day = day.substr(1);}// 查找月份的数字表示const char* monthNum = "00"; // 默认为无效月份for (int i = 0; i < 12; ++i) {if (month == months[i].short_name) {monthNum = months[i].num;break;}}// 格式化输出为 YYYY-MM-DD HH:MM:SSreturn year + "-" + monthNum + "-" + (day.size() == 1 ? "0" + day : day) + " " + __TIME__;
}
public:
// 返回编译日期并只执行一次
static const std::string& formated() {static const std::string formattedDate = formatCompileDate();return formattedDate;
}
};int main() {std::cout << "Compilation date : " << compileDate::formated()<< std::endl;return 0;
}
Usage:
[root@VM-24-13-centos cpp]# g++ __DATE__.cpp
[root@VM-24-13-centos cpp]# ./a.out
Compilation date : 2024-09-10 22:26:13
[root@VM-24-13-centos cpp]#