strftime和strptime函数对时间的转换操作

 1 #include <time.h>
 2 #include <stdio.h>
 3 
 4 int main()
 5 {
 6     struct tm * tm_ptr, timestruct;//定义一个tm结构的指针tm_ptr和tm结构的timestruct
 7     time_t the_time;        //定义一个time_t结构的the_time
 8     char buf[256];            //字符串缓冲区
 9     char *result;            //字符串指针result
10     
11     (void)time(&the_time);        //获取底层的时间值,返回到the_time的地址处
12     tm_ptr=localtime(&the_time);    //将获得的时间值转换成本地时间,储存在tm *类型的tm_ptr中
13     strftime(buf, 256, "%A %d %B, %I:%M %p",tm_ptr);//按照特定的格式打印时间到buf中
14     
15     printf("strftime gives: %s\n", buf);    //打印buf中的时间
16     
17     strcpy(buf,"Sat 26 July 2003, 17:53 will do fine");//将后面的字符串复制到前面的buf中
18     
19     printf("calling strptime with: %s\n", buf);//打印一句话
20     tm_ptr=&timestruct;//设置tm类型的timestruct的地址为tm_prr就是tm_ptr指向timestruct
21     
22     result=strptime(buf,"%a %d %b %Y, %R", tm_ptr);//格式化打印buf中的时间,返回一个指针指向处理字符后面的字符
23     printf("strptime consumed up to: %s\n", result);//打印上面的result
24     
25     printf("strptime gives:\n");//打印一句话
26     printf("date: %02d/%02d/%02d\n",tm_ptr->tm_year%100, tm_ptr->tm_mon+1, tm_ptr->tm_mday);
27     printf("time: %02d:%02d\n",tm_ptr->tm_hour, tm_ptr->tm_min);//tm_ptr是是上面的函数产生的tm *结构
28     exit(0);//%02d表示不够两位的补充0但是超过两位的有多少打印多少
29 }

实际的操作

1 jason@t61:~/桌面$ ./a.out 
2 strftime gives: Friday 26 June, 06:30 PM
3 calling strptime with: Sat 26 July 2003, 17:53 will do fine
4 strptime consumed up to:  will do fine
5 strptime gives:
6 date: 03/07/26
7 time: 17:53
8 jason@t61:~/桌面$ date
9 2015年 06月 26日 星期五 18:30:34 CST

//2015年06月26日 星期五 18时53分54秒

posted @ 2015-06-26 18:54  kongchung  阅读(928)  评论(0编辑  收藏  举报