#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;
}
|