linux 时间格式化函数strftime和strptime使用

linux 时间格式化函数strftime和strptime使用

这两个函数都是时间日期的格式控制函数,在功能上看起来正好相反。strftime将一个struct tm结构格式化为一个字符串,strptime则是将一个字符串格式化为一个struct  tm结构。

strftime

函数原型:size_t strftime(char *s,size_t maxsize,char *format,conststruct tm *timeptr)
strftime
函数对timeptr指向的tm结构所代表的时间和日期进行格式编排,其结果放在字符串s中。该字符串的长度被设置为(最少)maxsize个字符。格式字符串format用来对写入字符串的字符进行控制,它包含着将被传送到字符串里去的普通字符以及编排时间和日期格式的转换控制符。

输入:const struct tm *timeptr

输出:char *s,size_t maxsize,char *format

strftime函数库中原型:

/* Format TP into S according to FORMAT.Write no more than MAXSIZEcharacters and return the number of characters written, or 0 if it would exceedMAXSIZE.  */
extern size_t strftime (char *__restrict __s, size_t __maxsize,
      __const char *__restrict__format,
      __const struct tm *__restrict__tp) __THROW;


转换控制符见下表

转换控制符

说明

%a

星期几的简写形式

%A

星期几的全称

%b

月份的简写形式

%B

月份的全称

%c

日期和时间

%d

月份中的日期,0-31

%H

小时,00-23

%I

12进制小时钟点,01-12

%j

年份中的日期,001-366

%m

年份中的月份,01-12

%M

,00-59

%p

上午或下午

%S

,00-60

%u

星期几,1-7

%w

星期几,0-6

%x

当地格式的日期

%X

当地格式的时间

%y

年份中的最后两位数,00-99

%Y

%Z

地理时区名称

具体的控制转换符说明可以查看man.

strptime

函数原型: char *strptime(const char *buf,const char*format,struct tm *timeptr)

format字符串的构建方式和strftimeformat字符串完全一样,strptime返回一个指针,指向转换过程处理的最后一个字符后面的那个字符,

输入:const char *buf,const char *format

输出:struct tm *timeptr

 

strptime库函数原型

/* Parse Saccording to FORMAT and store binary time information in TP.
   The return value is a pointer to the firstunparsed character in S.  */
extern char*strptime (__const char *__restrict __s,
           __const char *__restrict __fmt,struct tm *__tp)
     __THROW;

实例代码:

#include <time.h>
#include <stdio.h>
#include <string.h>

int main() {
    struct tm tm; 
    char buf[255];
      
    strptime("24/Aug/2011:09:42:35", "%d/%b/%Y:%H:%M:%S" , &tm);
    printf("asctime:%s\n",asctime(&tm));

    memset(buf,0,sizeof(buf));
    strftime(buf, sizeof(buf), "%d %b %Y %H:%M", &tm);
    puts(buf);
    return 0;
   } 




 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值