C语言标准宏__DATE__格式化YY/MM/DD,不能用C语言标准库函数
时间: 2023-10-25 15:24:36 浏览: 107
C语言标准宏__DATE__的格式为"MMM DD YYYY",其中MMM为英文月份缩写,DD为日期,YYYY为年份。要将其格式化为YY/MM/DD的形式,可以使用下面的代码:
```
#include <stdio.h>
#define MONTH_LENGTH 3
int main() {
char date[] = __DATE__;
char month[MONTH_LENGTH + 1];
int day, year;
sscanf(date, "%s %d %d", month, &day, &year);
// 将月份缩写转换为数字
int month_num = 0;
if (strncmp(month, "Jan", MONTH_LENGTH) == 0) {
month_num = 1;
} else if (strncmp(month, "Feb", MONTH_LENGTH) == 0) {
month_num = 2;
} else if (strncmp(month, "Mar", MONTH_LENGTH) == 0) {
month_num = 3;
} else if (strncmp(month, "Apr", MONTH_LENGTH) == 0) {
month_num = 4;
} else if (strncmp(month, "May", MONTH_LENGTH) == 0) {
month_num = 5;
} else if (strncmp(month, "Jun", MONTH_LENGTH) == 0) {
month_num = 6;
} else if (strncmp(month, "Jul", MONTH_LENGTH) == 0) {
month_num = 7;
} else if (strncmp(month, "Aug", MONTH_LENGTH) == 0) {
month_num = 8;
} else if (strncmp(month, "Sep", MONTH_LENGTH) == 0) {
month_num = 9;
} else if (strncmp(month, "Oct", MONTH_LENGTH) == 0) {
month_num = 10;
} else if (strncmp(month, "Nov", MONTH_LENGTH) == 0) {
month_num = 11;
} else if (strncmp(month, "Dec", MONTH_LENGTH) == 0) {
month_num = 12;
}
// 输出YY/MM/DD格式的日期
printf("%02d/%02d/%02d\n", year % 100, month_num, day);
return 0;
}
```
该代码将__DATE__宏的值通过sscanf()函数解析为月份字符串、日期和年份,然后根据月份字符串确定月份的数字值。最后输出YY/MM/DD格式的日期。注意,需要使用strncmp()函数来比较字符串,因为月份缩写的长度可能不足3个字符。
阅读全文