相关文章推荐
风流的手术刀  ·  解决error C1083: ...·  昨天    · 
儒雅的太阳  ·  mysql ...·  2 周前    · 
刀枪不入的钥匙扣  ·  Kotlin 10. Kotlin ...·  1 月前    · 
想旅行的小笼包  ·  BitConverter.IsLittleE ...·  1 年前    · 
刚分手的卤蛋  ·  vb.net - Convert from ...·  1 年前    · 
腼腆的绿豆  ·  【Java 8 新特性】Java ...·  1 年前    · 
想表白的领结  ·  torch.backends.cudnn.b ...·  1 年前    · 

C++ 获取格式化时间戳的方法

获取时间戳是一个重要且常见的功能,通常在日志打印,请求响应过程中需要用到。通常精确到毫秒已经OK,一些情况下秒级也满足使用需求,这里记录一下自己开发过程获取时间戳的用法。

1.Linux系统函数 gettimeofday, 毫秒级时间戳

#include <sys/time.h>
//2021-10-06 13:13:09.935
static std::string getCurrentTime() {
    struct timeval tv;
    gettimeofday(&tv, NULL);
    static const int MAX_BUFFER_SIZE = 128;
    char timestamp_str[MAX_BUFFER_SIZE];
    time_t sec = static_cast<time_t>(tv.tv_sec);
    int ms = static_cast<int>(tv.tv_usec) / 1000;
    struct tm tm_time;
    localtime_r(&sec, &tm_time);
    static const char *formater = "%4d-%02d-%02d %02d:%02d:%02d.%03d";
    int wsize = snprintf(timestamp_str, MAX_BUFFER_SIZE, formater,
                        tm_time.tm_year + 1900, tm_time.tm_mon + 1, tm_time.tm_mday,
                        tm_time.tm_hour, tm_time.tm_min, tm_time.tm_sec, ms);
    timestamp_str[min(wsize, MAX_BUFFER_SIZE - 1)] = '\0';
    return std::string(timestamp_str);


2.使用标准库函数 chrono, 毫秒级时间戳

//2021-10-06 13:13:09.935
static std::string getCurrentTime() {
    auto now   = std::chrono::system_clock::now();
    auto now_ms = std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch());
    auto sectime   = std::chrono::duration_cast<std::chrono::seconds>(now_ms);
    int32_t milltime = millitime.count() % 1000;
    std::time_t timet = sectime.count();
    struct tm curtime;
    localtime_r(&timet, &curtime);
    char buffer[64];
    sprintf(buffer, "%4d-%02d-%02d %02d:%02d:%02d.%03d", curtime.tm_year + 1900, curtime.tm_mon + 1,
            curtime.tm_mday, curtime.tm_hour, curtime.tm_min, curtime.tm_sec, milltime);
    return std::string(buffer);

3.std::ctime, 秒级时间戳

//Wed Oct  6 13:13:09 2021
static std::string getCurrentTime0() {
    std::time_t result = std::time(nullptr);
    std::string ret;