41 - strftime()函数

1 函数原型

strftime()函数:时间类型转换,函数原型如下:

size_t strftime ( char* ptr, size_t maxsize, const char* format, const struct tm* timeptr );

ctime库描述如下:

Format time as string
1. Copies into ptr the content of format, expanding its format specifiers into the corresponding values that represent the time described in timeptr, with a limit of maxsize characters.
  1. strftime()函数:
    (1)根据指定的格式将时间和日期信息格式化为字符串。

2 参数

strftime()函数有四个参数ptr、maxsize、format和timeptr:

  1. 参数ptr是指向字符数组的指针,类型为char*;字符数组ptr用于存储格式化后的字符串;
  2. 参数maxsize是字符数组ptr可以存储的最大字符数(包括末尾的空字符’\0’),类型为size_t;
  3. 参数format是指向格式化字符串的指针,类型为char*;格式化字符串format指定如何将时间结构timeptr中的时间和日期信息格式化为字符串;
  4. 参数timeptr是一个指向struct tm类型的时间结构的指针,类型为struct tm*;时间结构timeptr包含要转换的日期和时间信息。

ctime库描述如下:

ptr
1. Pointer to the destination array where the resulting C string is copied.

maxsize
1. Maximum number of characters to be copied to ptr, including the terminating null-character.

format
1. C string containing any combination of regular characters and special format specifiers.
2. These format specifiers are replaced by the function to the corresponding values to represent the time specified in timeptr. 

timeptr
1.Pointer to a tm structure that contains a calendar time broken down into its components (see struct tm).

特别说明

  1. 格式化字符串包含普通字符和格式说明符;
  2. 格式说明符会被时间结构中对应的日期和时间信息替换;
  3. 常用格式说明符如下所示:
%Y:四位年份
%y:两位年份
%m:两位月份(01-12)
%d:两位日期(01-31)
%H:24小时制的小时(00-23)
%M:分钟(00-59)
%S:秒(00-60)
%A:星期几的全名
%a:星期几的缩写
%B:月份的全名
%b:月份的缩写
%p:AM 或 PM
%Z:时区名称
%c:日期和时间的完整格式
%x:日期的完整格式
%X:时间的完整格式

3 返回值

strftime()函数返回值类型为size_t类型,当格式化后的字符串的长度(包括末尾的空字符’\0’):

  1. ≤ maxsize,返回成功写入字符数组ptr的字符数(不包括末尾的空字符’\0’);
  2. > maxsize,返回0。

4 示例

示例代码如下所示:

int main() {
   //
   time_t current_time = 0;
   struct tm* current_time_tm = NULL;
   char time_buffer[80] = { 0 };
   // 获取当前时间
   current_time = time(NULL);
   // 将时间值转换为时间结构
   current_time_tm = localtime(&current_time);
   // 将时间结构转化为字符串
   strftime(time_buffer, sizeof(time_buffer), "%Y-%m-%d %H:%M:%S", current_time_tm);
   // 打印当前时间
   printf("当前时间: %s\n", time_buffer);
   //
   return 0;
}

代码运行结果如下图所示:

在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值