A portable way to create timestamps in c / c ++

I need to create a timestamp in this yyyymmdd format. Basically I want to create a file name with the current extension. (for example: log.20100817)

+4
source share
3 answers

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;
}
+18
source

Another alternative: Boost.Date_Time .

+1
source

++ 11:

std::time_t t = std::time(nullptr);
std::tm tm = *std::localtime(&t);
std::ostringstream oss;
oss << std::put_time( &tm, "%Y-%m-%d" );
std::string timestamp( oss.str() );

chrono ( sstream iomanip, put_time).

std::put_time. , , :

oss << std::put_time(&tm, "%Y-%m-%d_%H:%M");

auto :

auto t = std::time(nullptr);
auto tm = *std::localtime(&t);
std::ostringstream oss;
oss << std::put_time( &tm, "%Y-%m-%d" );
std::string timestamp( oss.str() );
0

Source: https://habr.com/ru/post/1760151/


All Articles