C/C++ let __DATE__ format to “YYYY-MM-DD“

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::map
    struct 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:SS
    return 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]#
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值