I wrote a function to get a current date and time in format: DD-MM-YYYY HH:MM:SS
. It works but let's say, its pretty ugly. How can I do exactly the same thing but simpler?
string currentDateToString()
{
time_t now = time(0);
tm *ltm = localtime(&now);
string dateString = "", tmp = "";
tmp = numToString(ltm->tm_mday);
if (tmp.length() == 1)
tmp.insert(0, "0");
dateString += tmp;
dateString += "-";
tmp = numToString(1 + ltm->tm_mon);
if (tmp.length() == 1)
tmp.insert(0, "0");
dateString += tmp;
dateString += "-";
tmp = numToString(1900 + ltm->tm_year);
dateString += tmp;
dateString += " ";
tmp = numToString(ltm->tm_hour);
if (tmp.length() == 1)
tmp.insert(0, "0");
dateString += tmp;
dateString += ":";
tmp = numToString(1 + ltm->tm_min);
if (tmp.length() == 1)
tmp.insert(0, "0");
dateString += tmp;
dateString += ":";
tmp = numToString(1 + ltm->tm_sec);
if (tmp.length() == 1)
tmp.insert(0, "0");
dateString += tmp;
return dateString;
}
I wanted to use the C++11 answer, but I could not because GCC 4.9 does not support std::put_time.
std::put_time implementation status in GCC?
I ended up using some C++11 to slightly improve the non-C++11 answer. For those that can't use GCC 5, but would still like some C++11 in their date/time format:
Using C++ in MS Visual Studio 2015 (14), I use:
Non C++11 solution: With the
<ctime>
header, you could usestrftime
. Make sure your buffer is large enough, you wouldn't want to overrun it and wreak havoc later.you can use asctime() function of time.h to get a string simply .
Sample output:
Since C++11 you could use
std::put_time
fromiomanip
header:std::put_time
is a stream manipulator, therefore it could be used together withstd::ostringstream
in order to convert the date to a string: