由于在程序中常遇到日志,性能统计一些功能的实现,需要获取当前系统的时间;
本文记录了获取当前系统时间的几种方法,以便使用和查找;
1.MFC库
1.使用CTime类的GetCurrentTime函数;
CTime t = CTime::GetCurrentTime();
int nYear = t.GetYear();
int nMonth = t.GetMonth();
int nDay = t.GetDay();
int nHour = t.GetHour();
int nMinute = t.GetMinute();
int nSecond = t.GetSecond();
CString str;
str.Format(_T("当前时间是:%d年%02d月%02d日 %02d:%02d:%02d"),nYear,nMonth,nDay,nHour,nMinute,nSecond);
AfxMessageBox(str);
2.使用time函数
time_t tt = time(NULL);
tm* pTime = localtime(&tt);
int nYear = pTime->tm_year+1900;
int nMonth = pTime->tm_mon+1;
int nDay = pTime->tm_mday;
int nHour = pTime->tm_hour;
int nMinute = pTime->tm_min;
int nSecond = pTime->tm_sec;
CString str;
str.Format(_T("当前时间是:%d年%02d月%02d日 %02d:%02d:%02d"),nYear,nMonth,nDay,nHour,nMinute,nSecond);
AfxMessageBox(str);
2.ctime库
C语言中,使用std::time函数和std::localtime函数可以获取当前时间(精确到秒)。
#include <ctime>
const std::string GetCurrentSystemTime_CTime()
{
std::time_t seconds_since_epoch = std::time(nullptr); // 获取从1970-01-01 00:00:00到现在的秒数
std::tm* ptm = std::localtime(&seconds_since_epoch); // 获取当前时间(精确到秒)
char date[60] = { 0 };
sprintf(date, "%d-%02d-%02d %02d:%02d:%02d",
(int)ptm->tm_year + 1900, (int)ptm->tm_mon + 1, (int)ptm->tm_mday,
(int)ptm->tm_hour, (int)ptm->tm_min, (int)ptm->tm_sec);
return move(std::string(date));
}
3.chrono库
使用std::chrono::system_clock::now()获取当前系统时间,转换为time_t后,显示;
精度在秒为单位;
// 获取当时系统时间
const std::string GetCurrentSystemTime()
{
time_t t = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
struct tm* ptm = localtime(&t);
char date[64] = { 0 };
sprintf(date, "%d-%02d-%02d %02d:%02d:%02d",
(int)ptm->tm_year + 1900, (int)ptm->tm_mon + 1, (int)ptm->tm_mday,
(int)ptm->tm_hour, (int)ptm->tm_min, (int)ptm->tm_sec);
return move(std::string(date));
}
使用函数time_point_now.time_since_epoch()和std::chrono::duration_cast<std::chrono::microseconds>将精度提高到微秒级别;
const std::string GetCurrentSystemTime_HighAccuracy()
{
// 获取当前时间点
std::chrono::system_clock::time_point time_point_now = std::chrono::system_clock::now();
// 从1970-01-01 00:00:00到当前时间点的时长
std::chrono::system_clock::duration duration_since_epoch = time_point_now.time_since_epoch();
// 将时长转换为微秒数
time_t microseconds_since_epoch = std::chrono::duration_cast<std::chrono::microseconds>(duration_since_epoch).count();
time_t seconds_since_epoch = microseconds_since_epoch / 1000000; // 将时长转换为秒数
std::tm* current_time = std::localtime(&seconds_since_epoch); // 获取当前时间(精确到秒)
time_t tm_microsec = microseconds_since_epoch % 1000; // 当前时间的微妙数
time_t tm_millisec = microseconds_since_epoch / 1000 % 1000; // 当前时间的毫秒数
char date[126] = { 0 };
sprintf(date, "%d-%02d-%02d %02d:%02d:%02d %03d#%03d",
(int)current_time->tm_year + 1900,
(int)current_time->tm_mon + 1,
(int)current_time->tm_mday,
(int)current_time->tm_hour,
(int)current_time->tm_min,
(int)current_time->tm_sec,
(int)tm_millisec,
(int)tm_microsec
);
return move(std::string(date));
}