Napisałem funkcję, aby uzyskać bieżącą datę i godzinę w formacie: DD-MM-YYYY HH:MM:SS
. Działa, ale załóżmy, że jest dość brzydka. Jak mogę zrobić dokładnie to samo, ale prostsze?Bieżąca data i czas w postaci ciągu znaków
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;
}
http://pubs.opengroup.org/onlinepubs/9699919799/functions/strftime.html – Mat
Czy nie byłoby prostsze korzystanie ze ['std :: strftime'] (http://en.cppreference.com/ w/cpp/chrono/c/strftime)? –
[Wzmocnienie - Data czasu] (http://www.boost.org/doc/libs/1_53_0/doc/html/date_time/examples.html#date_time.examples.dates_as_strings) – M456