C++获取时间戳
#include <iostream>
#include <chrono>
const std::string getCurrentSystemTime()
{
auto tt = std::chrono::system_clock::to_time_t
(std::chrono::system_clock::now());
struct tm* ptm = localtime(&tt);
char date[60] = {0};
sprintf(date, "%d%02d%02d %02d:%02d:%02d",
(int)ptm->tm_year + 1900,(int)ptm->tm_mon + 1,(int)ptm->tm_mday,
(int)ptm->tm_hour,(int)ptm->tm_min,(int)ptm->tm_sec);
return std::string(date);
}
uint getTime()
{
struct timespec tv;
clock_gettime(CLOCK_REALTIME,&tv);
uint sec= tv.tv_sec;
return sec;
}
int main(int argc, char* argv[]){
std::string timestamp=std::to_string(getTime());
std::cout<<timestamp<<std::endl;
std::string currentTime=getCurrentSystemTime();
std::cout<<currentTime<<std::endl;
}
getTime返回的是秒级别的时间戳
getCurrentSystemTime返回的是日期+时间
运行结果如下图