您的位置:首页 > 运维架构 > Linux

linux 下时间函数strftime()的用法

2011-05-29 18:48 525 查看
strftime() 函数将时间格式化
我们可以使用strftime()函数将时间格式化为我们想要的格式。它的原型如下:
size_t strftime(
char *strDest,
size_t maxsize,
const char *format,
const struct tm *timeptr
);
我们可以根据format指向字符串中格式命令把timeptr中保存的时间信息放在strDest指向的字符串中,最多向strDest中存放maxsize个字符。该函数返回向strDest指向的字符串中放置的字符数。
函数strftime()的操作有些类似于sprintf():识别以百分号(%)开始的格式命令集合,格式化输出结果放在一个字符串中。格式化命令说明 串 strDest中各种日期和时间信息的确切表示方法。格式串中的其他字符原样放进串中。格式命令列在下面,它们是区分大小写的。
%a 星期几的简写
%A 星期几的全称
%b 月分的简写
%B 月份的全称
%c 标准的日期的时间串
%C 年份的后两位数字
%d 十进制表示的每月的第几天
%D 月/天/年
%e 在两字符域中,十进制表示的每月的第几天
%F 年-月-日
%g 年份的后两位数字,使用基于周的年
%G 年分,使用基于周的年
%h 简写的月份名
%H 24小时制的小时
%I 12小时制的小时
%j 十进制表示的每年的第几天
%m 十进制表示的月份
%M 十时制表示的分钟数
%n 新行符

------------------------小例子------------------------

#include "time.h"
#include "stdio.h"
int main(void)
{
struct tm *ptr;
time_t lt;
char str[80];
lt=time(NULL);
ptr=localtime(<);
strftime(str,100,"It is now %I %p",ptr);
printf(str);
return 0;
}
其运行结果为:
It is now 4PM
而下面的程序则显示当前的完整日期:
#include<stdio.h>
#include<string.h>
#include<time.h>

int main( void )
{
struct tm *newtime;
char tmpbuf[128];
time_t lt1;

time( <1 );
newtime=localtime(<1);

strftime( tmpbuf, 128, "Today is %A, day %d of %B in the year %Y./n", newtime);
printf(tmpbuf);

return 0;
}

还有以下例子代码可以参考:

char * const getlogintime()//获得普通时间

{

time_t m_t;

m_t = time(&m_t);

strftime(pblgtime,20,"%Y-%m-%d %X",localtime(&m_t));

return pblgtime;

}

unsigned long getsec()//获得秒

{

rn_time = time( &rn_time );

return rn_time;

}

unsigned long getusec()//获得微秒时间

{

struct timeval tp;

long ntime;

gettimeofday(&tp,NULL);

rn_utime = tp.tv_usec;

return rn_utime;

}

int cmptime(int sec1,int usec1,int sec2, int usec2) //比较两个时间

{

if( sec1 >; sec2 )

{

return 1;

}

else

{

if( sec1 < sec2 )

{

return -1;

}

else

{

if( usec1 >; usec2 )

{

return 1;

}

else

{

if( usec1 < usec2 )

{

return -1;

}

else

return 0;

}

}

}

}

int main()

{

printf("%s/n",getlogintime());

printf("%ld/n",getsec());

printf("%ld/n",getusec());

sleep(3);

printf("%ld/n",getsec());

printf("%ld/n",getusec());

exit(0);

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: