函數說明
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