编程语言
首页 > 编程语言> > C++ 时间字符串的格式化输出

C++ 时间字符串的格式化输出

作者:互联网

1.Linux系统函数 gettimeofday, 毫秒级时间戳,需要包含头文件 #include <sys/time.h>

static std::string getCurrentTime()
{
  struct timeval tv;
  gettimeofday(&tv, NULL);

  static constexpr size_t MAX_BUFFER_SIZE = 128;
  char buff[MAX_BUFFER_SIZE + 1];
  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 ret = snprintf(buff, 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);
  if (ret < 0) {
    return std::string("");
  }

  return std::string(buff);
}

2.使用C++标准库函数 std::chrono

static std::string FormatTimePoint(const std::chrono::system_clock::time_point &time_point,
                                   const std::string &format = "%Y-%m-%d %X")
{
  auto in_time_t = std::chrono::system_clock::to_time_t(time_point);
  std::stringstream ss;
  ss << std::put_time(std::localtime(&in_time_t), format.c_str());
  return ss.str();
}

使用方法如下:

int main()
{
  // 方法一
  std::cout << getCurrentTime() << std::endl;
  // 方法二
  const std::chrono::time_point<std::chrono::system_clock> now =
      std::chrono::system_clock::now();
  std::cout << FormatTimePoint(now) << std::endl;
  return 0;
}

结果输出:

2022-03-25 12:17:57.336
2022-03-25 12:17:57

Process finished with exit code 0

标签:std,02d,格式化,tv,C++,tm,static,time,字符串
来源: https://www.cnblogs.com/sunwenqi/p/16054076.html