Chinaunix首页 | 论坛 | 博客
  • 博客访问: 313475
  • 博文数量: 43
  • 博客积分: 1044
  • 博客等级: 准尉
  • 技术积分: 658
  • 用 户 组: 普通用户
  • 注册时间: 2010-12-20 14:56
个人简介

人法地,地法天,天法道,道法自然。

文章分类

全部博文(43)

文章存档

2019年(1)

2013年(3)

2012年(15)

2011年(24)

分类: LINUX

2011-03-08 10:04:52

  1. #include <stdlib.h>
  2. #include <string.h>
  3. #include <time.h>
  4. #include <stdio.h>
  5. #include <errno.h>

  6. int str2time(char *time,struct tm *outtime)
  7. {
  8.     struct tm tm;
  9.     char temp[10] = {0};
  10.     
  11.     memset(&tm,0,sizeof(tm));
  12.     
  13.     if(time == NULL){
  14.         return -1;
  15.     }
  16.     
  17.     memset(temp,0,sizeof(temp));
  18.     strncpy(temp,time,4);
  19.     tm.tm_year = atoi(temp) - 1900;

  20.     memset(temp,0,sizeof(temp));
  21.     strncpy(temp,time+4,2);
  22.     tm.tm_mon = atoi(temp) - 1;
  23.     
  24.     memset(temp,0,sizeof(temp));
  25.     strncpy(temp,time+6,2);
  26.     tm.tm_mday = atoi(temp);
  27.     
  28.     memset(temp,0,sizeof(temp));
  29.     strncpy(temp,time+8,2);
  30.     tm.tm_hour = atoi(temp);
  31.     
  32.     memset(temp,0,sizeof(temp));
  33.     strncpy(temp,time+10,2);
  34.     tm.tm_min = atoi(temp);
  35.     
  36.     memset(temp,0,sizeof(temp));
  37.     strncpy(temp,time+12,2);
  38.     tm.tm_sec = atoi(temp);
  39.     
  40.     tm.tm_isdst = -1;
  41.     memcpy(outtime,&tm,sizeof(struct tm));
  42.     
  43.     return 0;
  44. }

  45. int lossFoTime(struct tm *current_tm,time_t loss_time)
  46. {
  47.     struct tm *temp_tm = NULL;
  48.     time_t temp_time = (time_t)0;

  49.     temp_time = mktime(current_tm);
  50.     if(temp_time == (time_t)-1)
  51.     {
  52.         printf("errno is %d , errno message is %s\n",errno,strerror(errno));
  53.         return -1;
  54.     }
  55.     
  56.     temp_time += loss_time;
  57.     
  58.     temp_tm = localtime(&temp_time);
  59.     if(temp_tm == NULL)
  60.       {
  61.         printf("errno is %d , errno message is %s\n",errno,strerror(errno));
  62.         return -1;
  63.     }
  64.     
  65.     memcpy(current_tm,temp_tm,sizeof(struct tm));
  66.     return 0;
  67. }

  68. int main()
  69. {
  70.     char t[] = "20110228123245";
  71.     char str_time[20] = { 0 };
  72.     time_t loss_time = 1234;
  73.     struct tm tm;

  74.     memset(&tm,0,sizeof(tm));
  75.     
  76.     if(str2time(t,&tm) != 0)
  77.     {
  78.         printf("str2time wrong!\n");
  79.         return -1;
  80.     }
  81.     
  82.     if(lossFoTime(&tm,loss_time) != 0)
  83.     {
  84.         printf("lossFoTime wrong!\n");
  85.         return -1;
  86.     }

  87.     strftime(str_time,sizeof(str_time),"%Y%m%d%H%M%S",&tm);
  88.     
  89.     printf("%s\n",str_time);
  90.     
  91.     return 0;
  92. }
阅读(1634) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~