C语言之自定义__DATE__与__TIME__

时间:2021-06-29 01:40:22
 1 /*******************************************************************
 2  *   > File Name: 05-ymd.c
 3  *   > Author: fly
 4  *   > Mail: XXXXXXXX@icode.com
 5  *   > Create Time: Thu Sep  7 16:43:30 2017
 6  ******************************************************************/
 7 
 8 #include <stdio.h>
 9 
10 // Retrieve year info
11 #define OS_YEAR     ((((__DATE__ [7] - '0') * 10 + (__DATE__ [8] - '0')) * 10 \
12                                     + (__DATE__ [9] - '0')) * 10 + (__DATE__ [10] - '0'))
13 
14 // Retrieve month info
15 #define OS_MONTH    (__DATE__ [2] == 'n' ? (__DATE__ [1] == 'a' ? 1 : 6) \
16                                 : __DATE__ [2] == 'b' ? 2 \
17                                 : __DATE__ [2] == 'r' ? (__DATE__ [0] == 'M' ? 3 : 4) \
18                                 : __DATE__ [2] == 'y' ? 5 \
19                                 : __DATE__ [2] == 'l' ? 7 \
20                                 : __DATE__ [2] == 'g' ? 8 \
21                                 : __DATE__ [2] == 'p' ? 9 \
22                                 : __DATE__ [2] == 't' ? 10 \
23                                 : __DATE__ [2] == 'v' ? 11 : 12)
24 
25 // Retrieve day info
26 #define OS_DAY      ((__DATE__ [4] == ' ' ? 0 : __DATE__ [4] - '0') * 10 \
27                                 + (__DATE__ [5] - '0'))
28 
29 // Retrieve hour info
30 #define OS_HOUR     ((__TIME__ [0] - '0') * 10 + (__TIME__ [1] - '0'))
31 
32 // Retrieve minute info
33 #define OS_MINUTE   ((__TIME__ [3] - '0') * 10 + (__TIME__ [4] - '0'))
34 
35 // Retrieve second info
36 #define OS_SECOND   ((__TIME__ [6] - '0') * 10 + (__TIME__ [7] - '0'))
37 
38 static char time_str[32]; //= "YYYYMMDDHHMMSSres";
39 
40 char *get_build_time(void)
41 {
42 #if (1)
43     sprintf(time_str,"%02d%02d%02d", OS_YEAR%100, OS_MONTH, OS_DAY);
44 #else
45     sprintf(time_str, "%04d%02d%02d%02d%02d%02d", OS_YEAR, OS_MONTH, OS_DAY, OS_HOUR, OS_MINUTE, OS_SECOND);
46 #endif
47 
48     return time_str;
49 }
50 
51 int main(int argc, char* argv[])
52 {
53     printf("build time :%s\tbuild date :%s\n", __TIME__, __DATE__);
54     printf("%s\n", get_build_time());
55 
56     return 0;
57 }