linux 下时间字符串和time_t类型之间的相互转化

时间:2020-11-25 17:52:06
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <string.h>


time_t ConvertStrtoTime(char * szTime)
{
tm tm_;
time_t t_;
strptime(szTime, "%Y-%m-%d %H:%M:%S", &tm_); //将字符串转换为tm时间
tm_.tm_isdst = -1;
t_ = mktime(&tm_); //将tm时间转换为秒时间
//t_ += 3600; //秒数加3600
return t_;

}

int main()
{
char szTime[128] = {0};
char szBuf[64] = {0};
time_t t;
tm sttm;
strcpy(szTime, "2015-09-01 17:57:47");
t = ConvertStrtoTime(szTime);
printf("t:%ld \n", t);

sttm = *localtime(&t);//输出时间
strftime(szBuf, 64, "%Y-%m-%d %H:%M:%S", &sttm);

printf("szBuf:%s \n", szBuf);
return 0;
}


运行效果:
[root@localhost time]# ./convert 
t:1441101467 
szBuf:2015-09-01 17:57:47 
[root@localhost time]#