开发者

portable way to create a timestamp in c/c++

I need to generate time-stamp in this format yyyymmdd. Basically I want to create a filename with current date extension. (for ex开发者_开发技巧ample: log.20100817)


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;
}


Another alternative: Boost.Date_Time.


A modern C++ answer:

#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;
}

All the format code are detailed on the std::put_time page.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜