【C++】如何輸出專業的時間戳

1.GetLocalTime與GetSystemTime區別

GetLocalTimeGetSystemTime是Windows API 函數,用來獲取當地的當前系統格林威治日期和時間,北京時間和格林威治時間兩者相差了8小時。(使用前需要include<Windows.h>)

函數原型 :
VOID GetLocalTime(
LPSYSTEMTIME lpSystemTime //address of system times structure
);

參數說明:
lpSystemTime: 指向一個用戶自定義包含日期和時間信息的類型爲 SYSTEMTIME 的變量,
該變量用來保存函數獲取的時間信息。此函數會把獲取的系統時間信息存儲到SYSTEMTIME結構體裏邊

typedef struct _SYSTEMTIME {
WORD wYear;
WORD wMonth;
WORD wDayOfWeek;
WORD wDay;
WORD wHour;
WORD wMinute;
WORD wSecond;
WORD wMilliseconds;
} SYSTEMTIME, *PSYSTEMTIME, *LPSYSTEMTIME;

2.時間戳生成

對Windows系統:

std::string getTimeStamp()
{
    char buf[1024];
    SYSTEMTIME systime;
    GetLocalTime(&systime);
    sprintf_s(buf, "%04d/%02d/%02d-%02d:%02d:%02d.%03d ", systime.wYear, systime.wMonth, systime.wDay,
              systime.wHour, systime.wMinute, systime.wSecond, systime.wMilliseconds);
    return std::string(buf);
}

在寫函數時即可調用getTimeStamp函數,精確到毫秒級輸出函數執行時的時刻,如下。
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章