如何使用 boost 或标准库在 C++17 中获取当前时间(以毫秒为单位)?我尝试使用 std::chrono:
int main()
{
const auto currentDateTime = std::chrono::system_clock::now();
const auto currentDateTimeTimeT = std::chrono::system_clock::to_time_t(currentDateTime);
const auto currentDateTimeLocalTime = *std::gmtime(¤tDateTimeTimeT);
char currentDateTimeArrStr[100];
std::strftime(currentDateTimeArrStr, 100, "%Y%m%d_%H%M%S.%f", ¤tDateTimeLocalTime);
std::clog << std::string(currentDateTimeArrStr) << std::endl;
}
但是 %f
格式仅在 python strftime
函数中实现,而不是在 C++ 中实现,并且使用 boost:
int main()
{
const auto date = boost::gregorian::day_clock::universal_day();
boost::gregorian::date d(date.year(), date.month(), date.day());
const auto time = boost::posix_time::second_clock::universal_time().time_of_day();
boost::posix_time::time_duration td(time.hours(), time.minutes(), time.seconds(), time.fractional_seconds());
std::stringstream ss;
ss << d << ' ' << td;
boost::posix_time::ptime pt(not_a_date_time);
ss >> pt;
std::cout << pt << std::endl;
}
但是 boost api 只提供total_milliseconds
。
我需要这样的输出:12:02:34.323232
最佳答案
所以只需打印时间点的毫秒数...
const auto ms = std::chrono::time_point_cast<std::chrono::milliseconds>(currentDateTime).time_since_epoch().count() % 1000;
std::clog << std::put_time(¤tDateTimeLocalTime, "%Y%m%d_%H%M%S")
<< "." << std::setfill('0') << std::setw(3) << ms << std::endl;
How can i get current time with millisecond in C++11
您已在 std::chrono::system_clock::now()
调用中获得当前时间。
关于c++ - 在 C++17 中获取以毫秒为单位的时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63033270/