1.指定time_t类型的时间,格式化为YYYYMMDDHH24MISS型的字符串
void timeToSting(time_t time1, char *szTime) 02 { 03 struct tm tm1; 04 05 #ifdef WIN32 06 tm1 = *localtime(&time1); 07 #else 08 localtime_r(&time1, &tm1 ); 09 #endif 10 sprintf( szTime, "%4.4d%2.2d%2.2d%2.2d%2.2d%2.2d", 11 tm1.tm_year+1900, tm1.tm_mon+1, tm1.tm_mday, 12 tm1.tm_hour, tm1.tm_min,tm1.tm_sec); 13 }
2.指定YYYY-MM-DD HH24:MI:SS型的时间,格式化为time_t型的时间
time_t stingToTime(char * szTime) 02 { 03 struct tm tm1; 04 time_t time1; 05 06 sscanf(szTime, "%4d-%2d-%2d %2d:%2d:%2d", 07 &tm1.tm_year, 08 &tm1.tm_mon, 09 &tm1.tm_mday, 10 &tm1.tm_hour, 11 &tm1.tm_min, 12 &tm1.tm_sec); 13 tm1.tm_year -= 1900; 14 tm1.tm_mon --; 15 tm1.tm_isdst=-1; 16 time1 = mktime(&tm1); 17 18 return time1; 19 }
自己实践的一个小例子:
#include<stdio.h> #include<string.h> #include<time.h> void timetostring(time_t times,char *buffer); time_t stringtotime(char *str); int main(int argc,char *argv[]) { int n; char tostring[30]; char buf[100]; time_t t; if(strcmp("-t",argv[1])==0) { //xxx -t 1359460358 t=atoi(argv[2]); timetostring(t,buf); printf("get date from seconds is:[%s]\n",buf); } else if(strcmp("-s",argv[1])==0) { //xxx -s 2013-01-29 19:52:38 sprintf(buf,"%s %s",argv[2],argv[3]); t=stringtotime(buf); printf("get seconds from date is:[%d]\n",t); } else { printf("error\n"); } return 0; } void timetostring(time_t times,char *buffer) { struct tm *tm_t=localtime(×); strftime(buffer,100,"%F %T",tm_t); //printf("%s\n",buffer); //2013-01-29 19:52:38 } time_t stringtotime(char *str) { struct tm tms; time_t times; sscanf(str,"%4d-%2d-%2d %2d:%2d:%2d",&tms.tm_year,&tms.tm_mon,&tms.tm_mday,&tms.tm_hour,&tms.tm_min,&tms.tm_sec); tms.tm_year-=1900; tms.tm_mon--; times=mktime(&tms); //printf("%d\n",times);//1359460358 return(times); }