C++時間戳獲取


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(&current_time_tmp, NULL);
char *p_local_time = NULL;
p_local_time = get_local_time(local_time_str, sizeof(local_time_str), &current_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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM