23

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?

R. Martinho Fernandes
  • 228,013
  • 71
  • 433
  • 510
KnowItAllWannabe
  • 12,972
  • 8
  • 50
  • 91

1 Answers1

21

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';
R. Martinho Fernandes
  • 228,013
  • 71
  • 433
  • 510
  • 12
    Im surprised with there is no *modern* way to print datetime data. We must use the old-style C APIs. But, well, `std::chrono` is a great advance in datetime matters. But no C++11 way to print time? – Manu343726 Jul 23 '13 at 17:54
  • 5
    @Manu343726 (http://home.roadrunner.com/~hinnant/bloomington/chrono_io.html) was not standardised (not sure if it was due to time pressures or for other reasons). – R. Martinho Fernandes Jul 23 '13 at 17:59
  • 2
    Not an answer to this question, however the following is I believe further information related to this question: http://home.roadrunner.com/~hinnant/date_algorithms.html . This link develops algorithms that convert to and from year/month/day triples and all implementations of `system_clock::time_point`. These algorithms could aid in developing the I/O the OP desires. – Howard Hinnant Aug 08 '13 at 02:37
  • 3
    Note: `std::put_time` is NOT supported in gcc < 5.0, see http://stackoverflow.com/a/14137287/209882 – Bar Feb 08 '16 at 16:05