曲径通幽论坛

标题: strftime [打印本页]

作者: beyes    时间: 2009-2-20 16:08
标题: strftime
为了在时间和日期格式上得到更精确的设置,Linux 和现代 类UNIX(UNIX-like)系统一般都提供 strftime()。

这相应的和 sprintf 的工作方式比较像,函数原型及定义:
#include <time.h>
size_t strftime(char *s, size_t maxsize, const char *format, struct tm *timeptr);

strftime() 函数对由 timeptr 指针所指向的 tm 结构体中的时间形式进行格式化安排。这个字符串由 maxsize 参数指定至少多少个字符产度。format 参数用来控制写向字符串的字符。像 printf() 函数,它包含可以传递到串中的常用字符以及对日期元素格式化的通过转换说明符。转换说明符如下所示:

Conversion Specifier                 Description
%a                                 当地星期几的名称缩写,如 Sun
%A                                 当地星期几的完整名称,如 Sunday
%b                                 当地月份的缩写
%B                                 当地月份的完整名称
%c                                  当地适当的日期与实践表示法
%d                                  月里的天数,值为 01-31
%H                                  24小时制表示的时数,00-23
%I                                   12小时制表示的时数,01-12
%j                                   一年中的天数,001-366
%m                                 月份,01-12
%M                                 分钟,00-59
%p                                   显示对应的AM 或 PM
%S                                   秒数, 00-59
%u                                   一星期中的星期几,范围0~6,星期天从0开始算起
%U                                  一年中的星期数,01-53,一月的第一个星期日开始为01
%w                                  一星期中的星期几,范围0~6,星期天从0开始算起
%x                                   本地格式表示日期
%y                                  一个世纪中的年份(00~99)
%Y                                   完整的公元年份表示
%Z                                   使用的失去名称
%%                                  '%' 符号

date 命令中常用的形式对应于 strftime() 函数里的格式串为:
 
"%a %b %d %H:%M:%S %Y"

测试代码
01 #include <time.h>
02 #include <stdio.h>
03 #include <stdlib.h>
04 #include <string.h>
05
06 int main()
07 {
08         struct tm *tm_ptr, timestruct;
09         time_t the_time;
10         char buf[256];
11         char *result;
12
13         (void)time(&the_time);
14         tm_ptr = localtime(&the_time);
15         strftime(buf, 256, "%A %d %B, %I:%S %p", tm_ptr);
16
17         printf("strftime gives: %s\n", buf);
18         exit(0)
19 }

运行及输出
[root@localhost C]# ./strftime.exe
strftime gives: Saturday 21 February, 09:58 AM





欢迎光临 曲径通幽论坛 (http://www.groad.net/bbs/) Powered by Discuz! X3.2