1. UNIX时间戳转成时间字符串函数
// Unixtime2Str.cpp
#include <iostream>
#include <time.h>
void gettimestr(time_t& time, tm* lotime,char* buf)
{
lotime = localtime(&time);
strftime(buf, 64, "%Y:%m:%d %H:%M:%S", lotime);
}
int main()
{
time_t t; //秒时间
tm* local; //本地时间
char buf[128]= {0};
t = time(NULL); //获取目前秒时间
gettimestr(t,local,buf);
std::cout << buf << std::endl;
}
2.时间字符串转成UNIX时间戳
#include <iostream>
#include <ctime>
#include <string.h>
using namespace std;
time_t strTime2unix(const char timeStamp[])
{
struct tm tm;
memset(&tm, 0, sizeof(tm));
sscanf(timeStamp, "%d:%d:%d %d:%d:%d", &tm.tm_year, &tm.tm_mon, &tm.tm_mday,&tm.tm_hour, &tm.tm_min, &tm.tm_sec);
tm.tm_year -= 1900;
tm.tm_mon--;
return mktime(&tm);
}
int main()
{
const char timeStamp[100] = "2022:10:03 22:41:40";
time_t t = strTime2unix(timeStamp);
cout << t << endl;
return 0;
}