#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct {
unsigned int Year;
unsigned char Month;
unsigned char Date;
unsigned char Hours;
unsigned char Minutes;
unsigned char Seconds;
} buildDateTime_t;
typedef enum { false = 0, true } bool;
bool GetCompileDateTime(buildDateTime_t *times) {
const char *pMonth[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
const char Date[12] = __DATE__; // __DATE__是当前编译的文件的编译日期 格式是Mmm:dd:yyyy 是字符串
const char Time[9] = __TIME__; // __TIME__是当前编译的文件的编译时间 格式是hh:mm:ss 是字符串
unsigned char i;
for (i = 0; i < 12; i++) {
if (memcmp(Date, pMonth[i], 3) == 0) {
times->Month = i + 1, i = 12;
}
}
times->Year = (unsigned int)atoi(Date + 7); // 完整年份2003 返回 2003
//times->Year = (unsigned int)atoi(Date + 7); // 两位年份 比如 2003 返回03
times->Date = (unsigned char)atoi(Date + 4);
times->Hours = (unsigned char)atoi(Time + 0);
times->Minutes = (unsigned char)atoi(Time + 4);
times->Seconds = (unsigned char)atoi(Time + 6);
return true;
}
int main() {
buildDateTime_t MyBuildDateTime;
GetCompileDateTime(&MyBuildDateTime);
printf("year:%d\n", MyBuildDateTime.Year);
printf("Month:%d\n", MyBuildDateTime.Month);
printf("Date:%d\n", MyBuildDateTime.Date);
printf("Hours:%d\n", MyBuildDateTime.Hours);
printf("Minutes:%d\n", MyBuildDateTime.Minutes);
printf("Seconds:%d\n", MyBuildDateTime.Seconds);
getchar();
return 0;
}
运行结果:
参考文章: