How to convert std::chrono::time_point to string

Update for C++20:

This can now easily be done in C++20:

#include <chrono>
#include <format>
#include <iostream>
#include <string>

int
main()
{
    using namespace std::chrono_literals;
    std::chrono::time_point tp = std::chrono::sys_days{2016y/1/16} + 11h + 25min;
    std::string s = std::format("{:%Y%m%d%H%M}", tp);
    std::cout << s << '\n';
}

Output:

201601161125

Demo.

Original Answer:

Howard Hinnant’s free, open source, header-only, portable date/time library is a modern way to do this that doesn’t traffic through the old C API, and doesn’t require that you discard all of your sub-second information. This library is also being proposed for standardization.

There is a lot of flexibility in formatting. The easiest way is to just stream out:

#include "date.h"
#include <iostream>

int
main()
{
    using namespace date;
    std::cout << std::chrono::system_clock::now() << '\n';
}

This just output for me:

2017-09-15 13:11:34.356648

The using namespace date; is required in order to find the streaming operator for the system_clock::time_point (it isn’t legal for my lib to insert it into namespace std::chrono). No information is lost in this format: the full precision of your system_clock::time_point will be output (microseconds where I ran this on macOS).

The full suite of strftime-like formatting flags is available for other formats, with minor extensions to handle things like fractional seconds. Here is another example that outputs with millisecond precision:

#include "date.h"
#include <iostream>

int
main()
{
    using namespace date;
    using namespace std::chrono;
    std::cout << format("%D %T %Z\n", floor<milliseconds>(system_clock::now()));
}

which just output for me:

09/15/17 13:17:40.466 UTC

Leave a Comment