1、C++11 h毫秒级转换
#include <iostream> #include <chrono> #include <cstdio> static time_t getTimeStamp() { std::chrono::time_point<std::chrono::system_clock, std::chrono::milliseconds> tp = std::chrono::time_point_cast<std::chrono::milliseconds>(std::chrono::system_clock::now()); auto tmp = std::chrono::duration_cast<std::chrono::milliseconds>(tp.time_since_epoch()); time_t timestamp = tmp.count(); //std::time_t timestamp = std::chrono::system_clock::to_time_t(tp); return timestamp; } static std::tm *gettm(long long timestamp) { auto milli = timestamp + (long long)8 * 60 * 60 * 1000; //此处转化为东八区北京时间,如果是其它时区需要按需求修改 auto mTime = std::chrono::milliseconds(milli); auto tp = std::chrono::time_point<std::chrono::system_clock, std::chrono::milliseconds>(mTime); auto tt = std::chrono::system_clock::to_time_t(tp); std::tm *now = gmtime(&tt); //printf("%4d年%02d月%02d日 %02d:%02d:%02d ", now->tm_year + 1900, now->tm_mon + 1, now->tm_mday, now->tm_hour, now->tm_min, now->tm_sec); return now; }
2、秒级别的
#include "iostream" #include "time.h" #include "string.h" using namespace std; int main() { time_t now; int unixTime = (int)time(&now); time_t tick = (time_t)unixTime; struct tm tm; char s[100]; tm = *localtime(&tick); strftime(s, sizeof(s), "%Y-%m-%d %H:%M:%S", &tm); printf("%d: %s ", (int)unixTime, s); return 0; }