简体   繁体   中英

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

另一种选择: 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM