10-4 格式化时间

1. 将时间戳或日历时间转化为字符串格式

        上一小节将时间戳与日历时间互相转换,获取到了 struct tm* 类型的 calendar 日历时间,但此时间并非字符串类型,不易于在页面展示。故可利用 asctime() ,传入 struct tm* 变量,直接获取日历时间字符串。也可利用 ctime() 函数,传入 time_t 类型的变量,直接获取时间戳对应的日历时间字符串。可以发现,传入的变量不同,但输出结果相同。

void TestChartime(){

  // 获取时间戳,日历时间
  time_t current_time = time(NULL);
  struct tm* calendar = localtime(&current_time);

  puts(asctime(calendar));     // Mon Aug  9 22:16:02 2021
  puts(ctime(&current_time));  // Mon Aug  9 22:16:02 2021
}

        但 asctime() 和 ctime() 函数的输出格式不太符合国人阅读方式,故需要利用 strftime() 函数去获取日历时间字符串,并保留有 "xxxx-xx-xx xx:xx:xx" 的时间格式。strftime() 函数需要提供四个参数,一是存储日历时间字符串的字符数组,二是此字符数组的大小,三是日历时间字符串的格式,四是原 struct tm 类型的日历时间的指针。返回值为日历时间字符串字符的个数。此外,"%Y-%m-%d %H:%M:%S" 和 "%F %T" 等价,两者代码结果相同。

void TestStrftime(){

  time_t current_time = time(NULL);
  struct tm* calendar = localtime(&current_time);

  // 2021-08-09 23:13:00,该格式19个字符,加上末尾的'\0',共20字符
  char calendar_time[20];
  
  // 四个参数,存储日历时间的字符数组,字符数组大小,存储的格式,原 tm 类型的日历时间指针
  // size_t size = strftime(calendar_time, 20, "%F %T", calendar);  // 注意,此代码与下行代码结果相同
  size_t size = strftime(calendar_time, 20, "%Y-%m-%d %H:%M:%S", calendar);

  printf("size: %d\n", size);  // size: 19
  puts(calendar_time);  // 2021-08-09 23:16:23
}

2. 生成 20210809232400999(年月日时分秒毫秒)格式的文件名

        年月日时分秒 格式可以利用 strftime() 函数进行获取,而毫秒格式需要自己添加。首先,利用 10-2 小节书写的 TimeInMillisecond() 获取当前时间的毫秒位,然后利用 sprintf() 函数将毫秒转为字符串并添加至 "年月日时分秒" 字符串之后。具体操作见下述代码。

void TestTimeFilename(){

  // 获取当前时间的毫秒
  long long current_time_in_ms = TimeInMillisecond();
  int current_time_millisecond = current_time_in_ms % 1000;

  time_t current_time = time(NULL);
  struct tm* calendar = localtime(&current_time);

  // 20210809233000999,最终生成 “年月日时分秒毫秒” 格式的文件名,字符个数 18
  char calendar_time[18];

  // 四个参数,存储日历时间的字符数组,字符数组大小,存储的格式,原 tm 类型的日历时间指针
  size_t size = strftime(calendar_time, 18, "%Y%m%d%H%M%S", calendar);

  // sprintf() 函数可以将指定格式的字符串添加到另一个字符串的任意字符位置
  // 此处将 "%03d" 的毫秒字符添加到 calendar_time 的第十四个字符位置
  sprintf(calendar_time + 14, "%03d", current_time_millisecond);

  puts(calendar_time);  // 20210809233317749
}

        注意,sprintf() 函数接收三个参数,第一个是原字符串的待拼接位置,第二个是待拼接参数的字符串格式,第三个是待拼接参数(非字符串)。返回值为拼接至原字符串的字符个数。

sprintf() : https://www.runoob.com/cprogramming/c-function-sprintf.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值