Firstly, std::time_t
indeed captures both date and time, since it generally represents seconds from January 1st, 1970.
There is no great support for handling dates in C++11. You still have to depend on boost if you don't wish to do it, mostly, manually. Here's how to do it manually.
You can use it—in a thread-safe way—together with any std::chrono::*clock
, such as std::system_clock
, like this:
std::string get_date_string(std::chrono::time_point t) {
auto as_time_t = std::chrono::system_clock::to_time_t(t);
struct tm tm;
if (::gmtime_r(&as_time_t, &tm))
if (std::strftime(some_buffer, sizeof(some_buffer), "%F", &tm))
return std::string{some_buffer};
throw std::runtime_error("Failed to get current date as string");
}
Somewhere else, you can issue:
get_date_string(std::system_clock::now());
The relatively good thing about this solution is that, at the API level, you're still using modern, portable C++ concepts such as std::chrono::time_point
, and of course, std::string
.