strftime()函数中的格式字符

本文详细介绍了time.h中的strftime函数,该函数可以将struct tm结构体转换为字符串形式,并支持多种日期时间格式化选项。例如,%a代表星期的缩写名称,%Y代表完整的年份等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

time.h中的strftime函数用于把struct tm转换为字符串输出,类似于printf,我们可以为其指定格式,下表是其使用的格式字符

 

来源:http://www.cplusplus.com/reference/clibrary/ctime/strftime/

specifierReplaced byExample
%aAbbreviated weekday name *Thu
%AFull weekday name *Thursday
%bAbbreviated month name *Aug
%BFull month name *August
%cDate and time representation *Thu Aug 23 14:55:02 2001
%dDay of the month (01-31)23
%HHour in 24h format (00-23)14
%IHour in 12h format (01-12)02
%jDay of the year (001-366)235
%mMonth as a decimal number (01-12)08
%MMinute (00-59)55
%pAM or PM designationPM
%SSecond (00-59)02
%UWeek number with the first Sunday as the first day of week one (00-53)33
%wWeekday as a decimal number with Sunday as 0 (0-6)4
%WWeek number with the first Monday as the first day of week one (00-53)34
%xDate representation *08/23/01
%XTime representation *14:55:02
%yYear, last two digits (00-99)01
%YYear2001
%ZTimezone name or abbreviationCDT
%%% sign%
* The specifiers whose description is marked with an asterisk (*) are locale-dependent.

 

 

### C语言中 `strftime` 函数的用法及示例 #### 1. 函数简介 `strftime` 是一个用于将时间结构体(`struct tm`)转换为指定格式字符串的时间处理函数。其功能强大,支持多种日期和时间格式化选项[^2]。 #### 2. 函数原型 ```c size_t strftime(char *ptr, size_t maxsize, const char *format, const struct tm *timeptr); ``` - 参数 `ptr`:指向存储结果字符串的缓冲区。 - 参数 `maxsize`:指定缓冲区的最大大小,以防止缓冲区溢出。 - 参数 `format`:指定日期和时间的格式字符串。 - 参数 `timeptr`:指向包含时间信息的 `struct tm` 结构体指针。 #### 3. 格式字符串 `strftime` 的格式字符串由普通字符格式说明符组成。以下是一些常用的格式说明符[^2]: | 格式说明符 | 描述 | 示例输出 | |------------|--------------------------|------------------| | `%Y` | 四位年份 | `2023` | | `%m` | 两位月份(01-12) | `12` | | `%d` | 两位日期(01-31) | `25` | | `%H` | 两位小时(24小时制,00-23)| `14` | | `%M` | 两位分钟(00-59) | `30` | | `%S` | 两位秒数(00-61) | `45` | | `%a` | 缩写星期几 | `Wed` | | `%A` | 完整星期几 | `Wednesday` | | `%b` | 缩写月份 | `Dec` | | `%B` | 完整月份 | `December` | #### 4. 示例代码 以下是一个使用 `strftime` 的示例程序[^2]: ```c #include <stdio.h> #include <stdlib.h> #include <time.h> int main(int argc, char** argv) { time_t now_time; struct tm *info; char buffer[80]; time(&now_time); // 获取当前时间戳 info = localtime(&now_time); // 将时间戳转换为本地时间 // 使用 strftime 格式化时间 strftime(buffer, 80, "%Y-%m-%d %H:%M:%S", info); printf("格式化的日期和时间 : %s\n", buffer); // 输出格式化后的日期和时间 return 0; } ``` #### 5. 注意事项 - 确保缓冲区大小足够大以容纳格式化后的字符串,否则可能导致未定义行为[^2]。 - 如果需要跨平台开发,注意不同系统对 `strftime` 的实现可能存在细微差异[^3]。 #### 6. 返回值 `strftime` 返回写入缓冲区的字符数(不包括终止空字符 `\0`)。如果缓冲区空间不足,则返回零[^2]。 --- ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值