vehomzzz
vehomzzz

Reputation: 44568

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)

Upvotes: 4

Views: 9451

Answers (3)

kebs
kebs

Reputation: 6707

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.

Upvotes: 1

Brandon Horsley
Brandon Horsley

Reputation: 8104

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

Upvotes: 20

decimus phostle
decimus phostle

Reputation: 1040

Another alternative: Boost.Date_Time.

Upvotes: 1

Related Questions