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?
In C++ 11, we can also use std::chrono::system_clock::now (), which returns a time point representing the current point in time. That’s all about printing the current date and time in C.
Following is a simple C implementation to get the current date and time –. In C++ 11, we can also use std::chrono::system_clock::now () which returns a time point representing the current point in time.
Here we have used chrono library to print current date and time . The chrono library is a flexible collection of types that tracks time with varying degrees of precision . The chrono library defines three main types as well as utility functions and common typedefs.
The time_t is not a primitive data type, rather it is a data type from the C ISO library define to store system's time value. This system's time values are returned from the standard library function named time (). The function ctime () returns a string that represents the local time based on tm (argument) timer.
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';
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With