What is the state of the art way to get date and time as string in c++11?
I know about std::put_time
, but the reference says I shall use it only in streams.
There is std::chrono::system_clock
which provides to_time_t
returning the time as time_t
and lacking the date, doesn't it?
I could use a stringstream like bames53: Outputting Date and Time in C++ using std::chrono but that seems to be a workaround.
C++ strftime() The strftime() function in C++ converts the given date and time from a given calendar time time to a null-terminated multibyte character string according to a format string. The strftime() function is defined in <ctime> header file.
Time type. Alias of a fundamental arithmetic type capable of representing times, as those returned by function time . For historical reasons, it is generally implemented as an integral value representing the number of seconds elapsed since 00:00 hours, Jan 1, 1970 UTC (i.e., a unix timestamp).
The difftime() function in C++ computes the difference between two times in seconds. The difftime() function is defined in <ctime> header file.
Using Howard Hinnant's free, open-source header-only datetime library, you can get the current UTC time as a std::string
in a single line of code:
std::string s = date::format("%F %T", std::chrono::system_clock::now());
I just ran this, and the string contains:
2017-03-30 17:05:13.400455
That's right, it even gives you the full precision. If you don't like that format, all of the strftime
formatting flags are available. If you want your local time, there is a timezone library also available, though it is not header only.
std::string s = date::format("%F %T %Z", date::make_zoned(date::current_zone(),
std::chrono::system_clock::now()));
Output:
2017-03-30 13:05:13.400455 EDT
A simpler solution using std::chrono:
#include <chrono>
using sysclock_t = std::chrono::system_clock;
std::string CurrentDate()
{
std::time_t now = sysclock_t::to_time_t(sysclock_t::now());
char buf[16] = { 0 };
std::strftime(buf, sizeof(buf), "%Y-%m-%d", std::localtime(&now));
return std::string(buf);
}
Remember to adjust the format as appropriate for the time too.
Note, however, that I suspect this will not work well for multithreaded code since std::localtime()
returns a pointer to an internal struct.
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