How print current time in C++11?

KnowItAllWannabe picture KnowItAllWannabe · Jul 23, 2013 · Viewed 15.8k times · Source

Is there an easy way in C++11 to print the current wall time using the appropriate formatting rules of the locale associated with the ostream being used?

What I really want to do is something like this:

myStream << std::chrono::system_clock::now();

and have the date and time printed in accord with whatever locale is associated with myStream. C++11 offers put_time, but it takes a formatting string, and I want the format to be determined by the locale associate with the stream. There's also time_put and time_put_byname, but based on the examples at cppreference.com, these functions are used in conjunction with put_time.

Is there no simple way to print a timepoint value without manually formatting it?

Answer

R. Martinho Fernandes picture R. Martinho Fernandes · Jul 23, 2013

You can use put_time with a format string like "%c". %c is the format specifier for the standard date and time string for the locale. The result looks like "Tue Jul 23 19:32:18 CEST 2013" on my machine (POSIX en_US locale, in a German timezone).

auto now = std::chrono::system_clock::now();
auto now_c = std::chrono::system_clock::to_time_t(now);
std::cout << std::put_time(std::localtime(&now_c), "%c") << '\n';