C++获取微妙级时间戳

一、使用C++11提供的std::chrono库

#include <chrono>
#include <ctime>
#include <iomanip>
#include <string>
std::string getTime()
{
    // 获取当前时间点
    auto now = std::chrono::system_clock::now();
    // 将时间长度转换为微秒数
    auto now_us = std::chrono::duration_cast<std::chrono::microseconds>(now.time_since_epoch());
    // 再转成tm格式
    auto now_time_t = std::chrono::system_clock::to_time_t(now);
    auto now_tm = std::localtime(&now_time_t);

    // 可以直接输出到标准输出
    // std::cout << std::put_time(now_tm, "%Y-%m-%d %H:%M:%S.") << std::setfill('0') << std::setw(6) << now_us.count() % 1000000 << std::endl;

    // 格式化字符,年月日时分秒
    std::string now_time_str;
    char buf[64];
    std::strftime(buf, sizeof(buf), "%Y-%m-%d %H:%M:%S", now_tm);
    now_time_str += buf;

    // 格式化微秒
    snprintf(buf, sizeof(buf), ".%06lld", now_us.count() % 1000000);
    now_time_str += buf;

    printf("%s\n", now_time_str.c_str());
    return now_time_str;
}

示例输出:

2023-01-01 06:01:22.834339

二、补充资料

std::strftime函数可以自定义时间格式:

三个参数:目标字符串缓冲区、缓冲区大小和格式化字符串。格式化字符串中可以包含各种占位符,用于指定输出的时间格式。
下面是一些常用的占位符:
%Y:年(四位数)
%m:月(01-12)
%d:日(01-31)
%H:小时(00-23)
%M:分钟(00-59)
%S:秒(00-60)
%z:时区偏移量(+0800)
%a:星期几的缩写(Sun、Mon、Tue、Wed、Thu、Fri、Sat)
%A:星期几的全称(Sunday、Monday、Tuesday、Wednesday、Thursday、Friday、Saturday)
%b:月份的缩写(Jan、Feb、Mar、Apr、May、Jun、Jul、Aug、Sep、Oct、Nov、Dec)
%B:月份的全称(January、February、March、April、May、June、July、August、September、October、November、December)

参考文章

[1] Date and time utilities

posted @ 2023-05-04 15:12  Macrored  阅读(937)  评论(0编辑  收藏  举报