#include <sys/time.h>
#include <stdio.h>
#include <unistd.h>
#include<iostream>
#include<string>
using namespace std;
string GetLocalTimeWithMs(void)
{
struct timeval curTime;
gettimeofday(&curTime, NULL);
int milli = curTime.tv_usec / 1000;
char buffer[80] = {0};
struct tm nowTime;
localtime_r(&curTime.tv_sec, &nowTime);//把得到的值存入临时分配的内存中,线程安全
strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", &nowTime);
char currentTime[84] = {0};
snprintf(currentTime, sizeof(currentTime), "%s:%03d", buffer, milli);
return currentTime;
}
int main()
{
std::string current_time = GetLocalTimeWithMs();
std::cout << current_time << std::endl;
return 0;
}
linux c 获得当前时间精确到毫秒
于 2022-03-11 14:50:42 首次发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)