• 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
    
  • 相关阅读:
    SQL里的EXISTS与in、not exists与not in
    N秒后自动跳转
    Array类型的扩展
    css中block与inline的区别
    数据绑定表达式语法(Eval,Bind区别)
    case
    SCOPE_IDENTITY、IDENT_CURRENT 和 @@IDENTITY的比较 (转载)
    内容随鼠标漂移
    IIS下下伪静态html(URL Rewrite)设置方法
    sql查询含有某列名的所有表
  • 原文地址:https://www.cnblogs.com/sunwenqi/p/16054076.html
Copyright © 2020-2023  润新知