Search code examples
c++c++11c++-chrono

Chrono duration to time string


I have a few lines of code that takes the system clock on my Windows machine and converts it to a double.

std::chrono::time_point<std::chrono::system_clock> currentNow = 
std::chrono::system_clock::now();
auto duration = currentNow.time_since_epoch();
double millis = static_cast<double>(std::chrono::duration_cast<std::chrono::milliseconds>(duration).count());
double origin_time = millis / 1000;

I would like to reverse this later on and convert the double to a string being the format YYYY-mm-dd HH:MM:SS.ffffffff

The first step I have right now is taking the double and passing it as a parameter to chrono::duration.

auto rep = std::chrono::duration<double>(origin_time);

How would I go about using the chrono library to achieve the string specified above, thanks!


Solution

  • Construct a new time_point containing the current epoch:

    auto epoch = std::chrono::time_point<std::chrono::system_clock>();
    

    Add your converted duration to this time_point:

    auto oldNow = epoch + std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::duration<double>(origin_time));
    

    Convert it into a std::time_t:

    auto t_c = std::chrono::system_clock::to_time_t(oldNow);
    

    Print it using formatting facilities for time_t:

    std::cout << std::put_time(std::localtime(&t_c), "%F %T");
    

    Example output:

    2020-01-10 18:45:48
    

    See it live!

    You'll notice it is missing the .ffffffff part. That's because std::put_time has no formatting option for it. You can easily calculate the value yourself and put it at the end of the string, if that's important for you.

    Also note that this is much better accomplished using C++20 chrono or Howard's Date library (which is basically the same thing, except for a few bits here and there) as noted in the comments by the man himself. For an overview on it, you may be interested in this answer.