当前位置: 首页 > news >正文

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::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]#
http://www.lryc.cn/news/434999.html

相关文章:

  • git如何灵活切换本地账号对应远程github的两个账号
  • Python中实现函数的递归调用
  • Multisim使用手册
  • 线程的六种状态
  • 全球热门剪辑软件大搜罗
  • swagger-bootstrap-ui页面空白,也没报错
  • 15.2 JDBC数据库编程2
  • Spark数据介绍
  • 【0基础】制作HTML网页小游戏——贪吃蛇(附详细解析)
  • Vscode python无法转到函数定义
  • Python中的上下文管理器(with语句)及其作用
  • CTK框架(八):服务追踪
  • [针对于个人用户] 显卡与计算卡性能对比表
  • 2024年智能录屏解决方案全攻略,从桌面到云端
  • CentOS7.9下snmp v3 inform搭建监控端
  • 水库大坝安全监测方案,双重守护,安全无忧
  • yolov8实现图片验证码识别
  • 代码随想录训练营 Day56打卡 图论part06 108. 冗余连接 109. 冗余连接II
  • QT天气预报
  • JavaWeb中处理 Web 请求的方式总结
  • React的事件与原生事件的执行顺序?
  • 【Java】Runtime与Properties获取系统信息
  • 基于SpringBoot的社团管理系统
  • UE5.3_跟一个插件—Socket.IO Client
  • 鸿蒙轻内核A核源码分析系列七 进程管理 (1)
  • qt QGraphicsScene场景坐标和场景内GraphicsItem局部坐标的相互转换
  • Windows与linux中docker的安装与使用
  • some electronic products
  • 刘润《关键跃升》读书笔记7
  • 带参宏定义