- 论坛徽章:
- 0
|
最后给出完整函数,下面再给一个实现相同功能的方法,总结于此:
#include <stdio.h>
#include <iostream>
#include <sys/time.h>
#include <string.h>
using namespace std;
int str_to_time(char *sdate){
printf("sdate:%s\n",sdate);
time_t t = time(NULL);
struct tm *betime = (struct tm*)malloc(sizeof(struct tm));//申请时间结构体空间
char year[5],mm[3],dd[3],h[3],i[3],s[3];//注意字符大少,
strncpy(year,sdate,4);
year[4]='\0';//加入结束字符
printf("year:%s\n",year);//第一次输出测试
if(strcmp(year,"0000")==0) return 0;
strncpy(mm,sdate+5,2);
mm[2]='\0';
printf("mm:%s\n",mm);
strncpy(dd,sdate+8,2);
dd[2]='\0';
printf("dd:%s\n",dd);
strncpy(h,sdate+11,2);
h[2]='\0';
printf("h:%s\n",h);
strncpy(i,sdate+14,2);
i[2]='\0';
printf("i:%s\n",i);
strncpy(s,sdate+17,2);
s[2]='\0';
printf("s:%s\n",s);
printf("mm:%s\n",mm);
printf("year:%s\n",year);//第二次打印测试
betime->tm_year = (int) (atol(year)-1900);//gdb时候减法后是long,这里转换为int
betime->tm_mon = atol(mm);
betime->tm_mday = atol(dd);
betime->tm_hour = atol(h);
betime->tm_min = atol(i);
betime->tm_sec = atol(s);
printf("i:%s\n",i);
t = timegm(betime);
int a = time(&t);
printf("a=%d\n",a);//测试输出
free(betime);//释放tm结构体内存
return a;
};
int main(int argc,char *argv[]){
char sdate[22];
snprintf(sdate,sizeof(sdate),"%s","2010-12-11 17:23:24")
//cout << sdate << endl;
int da = str_to_time(sdate);
printf("da=%d\n",da);
return 0;
} |
|