MountainDrew
MountainDrew

Reputation: 473

Create a human-readable timestamp and store in string in C++

I would like to create filenames with timestamps in them based on when the program was run, i.e.

logfile_2020-04-21_18:11:10.txt
logfile_2020-04-22_18:13:43.txt
...

I can get the timestamp (I think) with

std::chrono::steady_clock::time_point timestamp = std::chrono::steady_clock::now();

but I don't know how to convert that into a string, much less a human-readable string.

The exact format of the timestamps doesn't matter, as long as it has the full date and time. Is there a simple way to do this in C++ using standard libraries?

Upvotes: 2

Views: 3548

Answers (1)

Martin Konrad
Martin Konrad

Reputation: 1095

What you're asking for is not defined. Your timestamp is coming from a "steady" clock which guarantees monotonic time but is not related to wall clock time and thus cannot be converted into a human-readable timestamp (think about what happens if you adjust your system time -1 min, a monotonic clock can never be adjusted like this!). Monotonic clocks often count from system start. If you want to print timestamps you most likely want to use std::chrono::system_clock - for example like so:

#include <iostream>
#include <chrono>
#include <iomanip>

int main() {
  auto timestamp = std::chrono::system_clock::now();

  std::time_t now_tt = std::chrono::system_clock::to_time_t(timestamp);
  std::tm tm = *std::localtime(&now_tt);

  std::cout << std::put_time(&tm, "%c %Z") << '\n';
  return 0;
}

You can find more information on formatting the date/time in the std::put_time() documentation.

Warning: std::localtime may not be thread safe! Check the documentation of your standard library if you intend to use it in a multi-threaded context. Sometimes a reentrant version is provided as well (often called localtime_r).

Upvotes: 2

Related Questions