linux c 中英文日期格式

20 篇文章 1 订阅

函数说明

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 
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值