函数说明
setlocale位于locale.h
头文件
setlocale(LC_TIME,"zh_CN.UTF-8");1
表示设置日期编码格式,这里设置为中文的日期格式
strftime位于time.h
头文件
strftime
格式化struct tm
日期,受setlocale(LC_TIME,"zh_CN.UTF-8");
的影响。
测试
#include <time.h>
#include <locale.h>
#include <stdio.h>
/*获取当前日期*/
const char*
sysutil_get_current_date(void)
{
static char datebuf[64];
time_t curr_time;
const struct tm* p_tm;
int i = 0;
curr_time = time(NULL);
p_tm = localtime(&curr_time);
if (strftime(datebuf, sizeof(datebuf), "%Y %b!%d %a %H:%M:%S ", p_tm) == 0) {
fprintf(stderr, "strftime");
}
datebuf[sizeof(datebuf) - 1] = '\0';
/* This hack is because %e in strftime() isn't so portable */
while (datebuf[i] != '!' && datebuf[i] != '\0') {
++i;
}
if (datebuf[i] == '!') {
datebuf[i] = ' ';
if (datebuf[i+1] == '0') {
datebuf[i+1] = ' ';
}
}
return datebuf;
}
int main(int argv, char * argc[])
{
printf("前: %s\n", sysutil_get_current_date()); // 英文日期格式的输出
setlocale(LC_TIME,"zh_CN.UTF-8"); // 设置为中文日期编码格式
printf("后: %s\n", sysutil_get_current_date()); //中文日期格式的输出
return 0;
}
lmz@X280:~/code/c/test$ gcc test_strftime.c -o test_strftime
lmz@X280:~/code/c/test$ ./test_strftime
前: 2020 May 26 Tue 08:37:47
后: 2020 5月 26 二 08:37:47