我写了一个函数来获取当前日期和时间的格式:DD-MM-YYYY HH:MM:SS
。它可以工作,但让我们说,它相当丑陋。我怎么能做完全相同的事情但更简单?
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;
}
7条答案
按热度按时间omqzjyyz1#
从C++11开始,你可以从
iomanip
头文件中使用std::put_time
:std::put_time
是一个流操作器,因此它可以与std::ostringstream
一起使用,以便将日期转换为字符串:c7rzv4ha2#
非C++11解决方案:对于
<ctime>
头文件,您可以使用strftime
。请确保您的缓冲区足够大,您不希望它溢出并在以后造成严重破坏。8ulbf1ek3#
你可以使用time. h的asctime()函数来简单地获取一个字符串。
样本输出:
toiithl64#
在C++20中,时间点格式化(字符串)在(chrono)标准库中可用。https://en.cppreference.com/w/cpp/chrono/system_clock/formatter
产出
它可以在Visual Studio 2019(v16.11.5)中使用最新的 C++ 版本(/std:c++latest)。
2uluyalo5#
在MS Visual Studio 2015(14)中使用C++,我用途:
mepcadol6#
fafcakar7#
我想使用C11的答案,但我不能,因为GCC 4.9不支持std::put_time。
std::put_time implementation status in GCC?
我最终使用了一些C11来稍微改进非C11的答案。对于那些不能使用GCC 5,但仍然希望使用C11的日期/时间格式的人: