C++时间工具类——纳秒,微秒,毫秒,秒,日期

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_=0;
        	if(LocalTime /1000000000 > 0)
		    {
			     time_ = (tm->tm_hour*10000+tm->tm_min*100+tm->tm_sec)*1000+LocalTime%1000000000/1000000;
		    }else
		    {
			    time_ = LocalTime%1000000000/1000000;
		    }
		return time_;	//精度毫秒 
	}
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值