How to generate filename based on current date & time in C++ using chrono

Problem:

You want to generate a filename, e.g., for datalogging, that contains the current date and time in C++ – for example:

2023-04-22_19-38-34.csv

Solution:

To generate a filename with the current date and time in C++, you can use the chrono library to get the current time and format it as a string. Here’s a code snippet that shows how to do this:

#include <chrono>
#include <iomanip>
#include <sstream>

std::string GetFilenameByCurrentDate(const char* extension=".bin") {
    // Get the current time
    auto now = std::chrono::system_clock::now();

    // Convert to local time
    auto localTime = std::chrono::system_clock::to_time_t(now);

    // Format the timestamp as a string
    std::stringstream ss;
    ss << std::put_time(std::localtime(&localTime), "%F_%H-%M-%S") << extension;
    return ss.str();
}

 

This function takes an optional extension parameter that specifies the file extension to use (by default, “.bin”). It uses the chrono library to get the current time (now), convert it to local time (localTime), and format it as a string (ss). The put_time function is used to format the time as a string in the format “%F_%H-%M-%S”, which represents the date and time in ISO 8601 format (e.g., 2023-04-23_19-13-22).

This will produce a filename such as 2023-04-23_19-13-22.bin, which can be used to create a new file or to store data in an existing file. By including a timestamp in the filename, you can easily keep track of when the file was created and quickly identify files that were created at a particular time.