【问题标题】:portable way to create a timestamp in c/c++在 C/C++ 中创建时间戳的可移植方式
【发布时间】:2010-08-17 17:49:11
【问题描述】:

我需要以这种格式 yyyymmdd 生成时间戳。基本上我想创建一个具有当前日期扩展名的文件名。 (例如:log.20100817)

【问题讨论】:

    标签: c++ c


    【解决方案1】:

    strftime

    #include <stdio.h>
    #include <stdlib.h>
    #include <time.h>
    
    int main()
    {
      char date[9];
      time_t t = time(0);
      struct tm *tm;
    
      tm = gmtime(&t);
      strftime(date, sizeof(date), "%Y%m%d", tm);
      printf("log.%s\n", date);
      return EXIT_SUCCESS;
    }
    

    【讨论】:

    • 您实际上并不需要 tm 临时值 - 您可以将 gmtime(&amp;t) 的返回值直接传递给 strftime()
    • @caf:我认为重点是展示gmtime 返回的内容。通常你不会只打印它。
    【解决方案2】:

    另一种选择:Boost.Date_Time

    【讨论】:

      【解决方案3】:

      现代C++ 答案:

      #include <iomanip>
      #include <sstream>
      #include <string>
      
      std::string create_timestamp()
      {
          auto current_time = std::time(nullptr);
          tm time_info{};
          const auto local_time_error = localtime_s(&time_info, &current_time);
          if (local_time_error != 0)
          {
              throw std::runtime_error("localtime_s() failed: " + std::to_string(local_time_error));
          }
          std::ostringstream output_stream;
          output_stream << std::put_time(&time_info, "%Y-%m-%d_%H-%M");
          std::string timestamp(output_stream.str());
          return timestamp;
      }
      

      所有格式代码在std::put_time页面上都有详细说明。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-09-20
        • 2011-01-09
        • 2010-10-27
        • 2010-10-02
        • 2018-06-23
        • 1970-01-01
        • 1970-01-01
        • 2013-01-25
        相关资源
        最近更新 更多