[英]Get current time in milliseconds, or HH:MM:SS:MMM format
我编写了一个 C++ 函数来以HH:MM:SS
格式获取当前时间。 如何添加毫秒或纳秒,以便我可以使用类似HH:MM:SS:MMM
的格式? 如果不可能,以毫秒为单位返回当前时间的函数也很好。 然后我可以自己计算两个日志点之间的相对时间距离。
string get_time()
{
time_t t = time(0); // get time now
struct tm * now = localtime(&t);
std::stringstream sstm;
sstm << (now->tm_hour) << ':' << (now->tm_min) << ':' << now->tm_sec;
string s = sstm.str();
return s;
}
这是使用C++11
chrono 库的可移植方法:
#include <chrono>
#include <ctime>
#include <iomanip>
#include <sstream>
#include <string>
// ...
std::string time_in_HH_MM_SS_MMM()
{
using namespace std::chrono;
// get current time
auto now = system_clock::now();
// get number of milliseconds for the current second
// (remainder after division into seconds)
auto ms = duration_cast<milliseconds>(now.time_since_epoch()) % 1000;
// convert to std::time_t in order to convert to std::tm (broken time)
auto timer = system_clock::to_time_t(now);
// convert to broken time
std::tm bt = *std::localtime(&timer);
std::ostringstream oss;
oss << std::put_time(&bt, "%H:%M:%S"); // HH:MM:SS
oss << '.' << std::setfill('0') << std::setw(3) << ms.count();
return oss.str();
}
这是使用 HowardHinnant日期库的更简洁的解决方案。
std::string get_time()
{
using namespace std::chrono;
auto now = time_point_cast<milliseconds>(system_clock::now());
return date::format("%T", now);
}
对于窗户,也许:
#include <iostream>
#include <Windows.h>
#include <strsafe.h>
int main()
{
CHAR sysTimeStr[13] = {};
SYSTEMTIME systemTime;
GetLocalTime(&systemTime);
sprintf_s(sysTimeStr,
"%u:%02u:%02u:%03u",
systemTime.wHour,
systemTime.wMinute,
systemTime.wSecond,
systemTime.wMilliseconds);
std::cout << sysTimeStr;
}
不要使用time()
(自纪元以来的秒数),而是尝试gettimeofday()
。 为您提供一个包含微秒字段的结构。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.