zoukankan      html  css  js  c++  java
  • 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
    ", p_local_time);

    这是基于 ctime 和 timeval 结构体实现的对当前系统时间的可视化,精确到 ms,一般情况下精度是足够了。


    参考资料

    [1] 【Linux编程】如何将gettimeofday获取的时间信息转换成可显示的字符串时间? https://blog.csdn.net/szullc/article/details/84946251

  • 相关阅读:
    Java SE
    Java SE
    Java SE
    Java SE
    Vocabulary: dockyard
    Vocabulary: Intercept
    Java SE
    MVG
    相关学习
    相机开发
  • 原文地址:https://www.cnblogs.com/phillee/p/13344160.html
Copyright © 2011-2022 走看看