1、找一個比較全的時間工具類太難了,沒人總結啊(適用於linux)。
#include <ctime>
#include <stdint.h>
#include <iostream>
#include <string>
#include <sys/time.h>
using std::string;
/**
* Linux高精度struct timespec(精確到納秒)和struct timeval(精確到微秒)
* */
class TimesUtil
{
public:
/**
* 獲取當前系統時間(精確到納秒)tv_nsec精確到納秒(編譯時加上-lrt)
* */
static inline int64_t getTimeNs()
{
struct timespec ts;
clock_gettime(CLOCK_REALTIME, &ts);
return ts.tv_sec*1000000000 + ts.tv_nsec;
}
/**
* 獲取當前系統時間(精度微秒)tv_usec精確到微秒
* */
static inline int64_t getTimeUs()
{
struct timeval tv;
gettimeofday(&tv, NULL);
return tv.tv_sec*1000000 + tv.tv_usec;
}
/**
* 獲取當前系統時間(精度毫秒)tv_usec精確到微秒
* */
static inline int64_t getTimeMs()
{
struct timeval tv;
gettimeofday(&tv, NULL);
return tv.tv_sec*1000 + tv.tv_usec/1000;
}
/**
* 獲取當前系統時間(精度秒),YY年 mm月 dd日 HH時 MM分 SS秒
* */
static inline string getDateTime()
{
time_t now = time(0);
tm *ltm = localtime(&now);
char myDate[40],myTime[40], ims[10];
strftime(myDate, 40, "%Y-%m-%d", ltm);
strftime(myTime, 40, " %H:%M:%S", ltm);
return string(myDate) + string(myTime);
}
/**
* 根據納秒時間返回 交易所時間格式:HHMMSSsss,其中LocalTime精確到納秒
**/
static int getLocalTime_t(int64_t LocalTime)
{
time_t local_time = LocalTime /1000000000;
struct tm* tm;
tm = localtime(&local_time);
int time_ = (tm->tm_hour*10000+tm->tm_min*100+tm->tm_sec)*1000+LocalTime%1000000000/1000000;
return time_;
}
};