gettimeofday

gettimeofday函数是Linux系统下标准C函数,在Windows下使用会返回-1错误
Linux调用方式:
#include <stdio.h> 
#include <sys/time.h> //添加头文件
int64_t getCurrentTime()      //直接调用这个函数就行了,返回值最好是int64_t,long long应该也可以
{    

   struct timeval tv;    
   gettimeofday(&tv,NULL);    //该函数在sys/time.h头文件中
   return ((long long)tv.tv_sec) * 1000 + tv.tv_usec / 1000;    
}    
注意:2038年以后,由于tv.tv_sec超出32位整型,所以就会溢出,保险的做法是进行类型强制转换
Windows系统调用getimeofday,会返回-1错误。可以编写一个函数替代该函数
#include <time.h>
#ifdef WIN32
#include <windows.h>
#else
include <sys/time.h>
#endif
#ifdef WIN32
int gettimeofday(struct timeval tp, void tzp)
{
time_t clock;
struct tm tm;
SYSTEMTIME wtm;
GetLocalTime(&wtm);
tm.tm_year = wtm.wYear - 1900;
tm.tm_mon = wtm.wMonth - 1;
tm.tm_mday = wtm.wDay;
tm.tm_hour = wtm.wHour;
tm.tm_min = wtm.wMinute;
tm.tm_sec = wtm.wSecond;
tm. tm_isdst = -1;
clock = mktime(&tm);
tp->tv_sec = clock;
tp->tv_usec = wtm.wMilliseconds * 1000;
return (0);
}
#endif

Boost获取系统时间格式化字符串

头文件

#include <boost/date_time/posix_time/posix_time.hpp>


代码

std::string strDateTime = boost::posix_time::to_simple_string(boost::posix_time::microsec_clock::local_time());

结果:2020-Jan-07 02:54:29.985437


1)携带毫秒

std::string strTime = boost::posix_time::to_iso_string(boost::posix_time::microsec_clock::local_time());

//20200403T163129.188138

strTime.insert(4, "-");

strTime.insert(7, "-");

int pos = strTime.find('T');

strTime.replace(pos, 1, std::string(" "));

strTime.insert(13, ":");

strTime.insert(16, ":"); 结果:2020-04-03 16:31:29.188138

2)携带秒

std::string strTime = boost::posix_time::to_iso_string(boost::posix_time::second_clock::local_time());

//20200403T163129

strTime.insert(4, "-");

strTime.insert(7, "-");

int pos = strTime.find('T');

strTime.replace(pos, 1, std::string(" "));

strTime.insert(13, ":");

strTime.insert(16, ":"); 结果:2020-04-03 16:31:29


注意:在Windows下运行获取的跟系统时间一样。在Linux下编译运行获取的跟系统的时间,可能相差8个小时,这个时候,需要设置系统的时区时间,执行如下指令:

[root@taishan-atlas huawei_linux_centos_7.6]# cp /usr/share/zoneinfo/Asia/Shanghai /etc/localtime  

cp: overwrite '/etc/localtime'? y