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

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

#include

#include

int main( void )

{

struct tm *newtime;

char tmpbuf[128];

time_t lt1;

time( &lt1 );

newtime=localtime(&lt1);

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);

}

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值