1. tm 結構體
在標準C/C++中,我們可通過tm結構來獲得日期和時間,tm結構在time.h中的定義如下:
#ifndef _TM_DEFINED struct tm { int tm_sec; /* 秒 – 取值區間爲[0,59] */ int tm_min; /* 分 - 取值區間爲[0,59] */ int tm_hour; /* 時 - 取值區間爲[0,23] */ int tm_mday; /* 一個月中的日期 - 取值區間爲[1,31] */ int tm_mon; /* 月份(從一月開始,0代表一月) - 取值區間爲[0,11] */ int tm_year; /* 年份,其值等於實際年份減去1900 */ int tm_wday; /* 星期 – 取值區間爲[0,6],其中0代表星期天,1代表星期一,以此類推 */ int tm_yday; /* 從每年的1月1日開始的天數 – 取值區間爲[0,365],其中0代表1月1日,1代表1月2日,以此類推 */ int tm_isdst; /* 夏令時標識符,實行夏令時的時候,tm_isdst爲正。不實行夏令時的進候,tm_isdst爲0;不瞭解情況時,tm_isdst()爲負。*/ }; #define _TM_DEFINED #endif
std::put_time()函數
https://www.yiibai.com/cpp_standard_library/cpp_put_time.html
2. 當前時間戳
#include <sys/time.h> #include <ctime> static char* get_local_time(char *time_str, int len, struct timeval *tv) { struct tm* ptm; char time_string[40]; long milliseconds; ptm = localtime (&(tv->tv_sec)); // Output format: 2018-12-09 10:52:57.200 strftime(time_string, sizeof(time_string), "%Y-%m-%d %H:%M:%S", ptm); milliseconds = tv->tv_usec/1000; snprintf (time_str, len, "%s.%03ld", time_string, milliseconds); return time_str; } char local_time_str[128]; timeval current_time_tmp; gettimeofday(¤t_time_tmp, NULL); char *p_local_time = NULL; p_local_time = get_local_time(local_time_str, sizeof(local_time_str), ¤t_time_tmp); printf("current_time_tmp %s\n", p_local_time);
這是基於 ctime 和 timeval 結構體實現的對當前系統時間的可視化,精確到 ms,一般情況下精度是足夠了。
參考資料
[1] 【Linux編程】如何將gettimeofday獲取的時間信息轉換成可顯示的字符串時間? https://blog.csdn.net/szullc/article/details/84946251