#include <sys/time.h>
#include <iomanip>
#include <sstream>
std::string getCurrentTime() {
struct timeval tv;
gettimeofday(&tv, NULL);
time_t t = tv.tv_sec;
struct tm *tm = localtime(&t);
std::ostringstream oss;
oss << std::setfill('0') << std::setw(4) << tm->tm_year + 1900
<< std::setw(2) << tm->tm_mon + 1
<< std::setw(2) << tm->tm_mday
<< std::setw(2) << tm->tm_hour
<< std::setw(2) << tm->tm_min
<< std::setw(2) << tm->tm_sec;
return oss.str();
}
该函数首先使用gettimeofday函数获取当前时间,并将struct timeval类型的tv_sec成员转换为time_t类型。接着,使用localtime函数将time_t类型的时间戳转换为struct tm类型的日期时间信息,并使用ostringstream流将其按照指定格式输出。
在输出过程中,使用std::setw和std::setfill函数对输出的数字进行补位和填充操作。具体来说,将年、月、日、时、分、秒分别按照4位、2位、2位、2位、2位、2位的格式输出,并使用0进行填充,以保证输出结果的字符串长度一致。
例如,如果在2023年5月11日14时05分03秒执行该函数,则返回的字符串应该为"20230511140503"。