Linux下字符串转时间tm结构函数strptime

来源:互联网 发布:手机视频直播软件 编辑:程序博客网 时间:2024/06/06 09:00

http://blog.csdn.net/yasaken/article/details/7429506

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

buf:                       tm格式化后的C字符串(以0结尾);
format:                 字符串格式,构建方式与strftime的format字符串完全一样;
struct tm *timeptr:转换后存储tm值的指针;
返回值:                指向转换过程处理的最后一个字符后面的那个字符。

功能:
将一个字符串格式化为一个tm结构,功能与strftime相反。

format参数:

转换控制符 说明
%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 地理时区名称


测试程序

#define _XOPEN_SOURCE /* glibc2 needs this */#include <stdio.h>#include <time.h>int main(void)  {      time_t lt      = time( NULL );    struct tm* ptr = localtime( lt );      char szBuffer[64] = {0};      const char* pFormat = "The time now is %Y-%m-%d %H:%M:%S";    // struct tm -> string    strftime(szBuffer, 64, pFormat, ptr);    printf("%s\n", szBuffer);        struct tm tmTemp;      char tmBuffer[64] = {0};    // string -> struct tm    strptime(szBuffer, pFormat, &tmTemp);    strftime(tmBuffer, 64, "The time just was %Y-%m-%d %H:%M:%S", &tmTemp);      printf("%s\n", tmBuffer);    return 0;  }

结果:

The time now is 2014-04-12 19:20:25
The time just was 2014-04-12 19:20:25

0 0