【发布时间】:2020-07-22 11:36:16
【问题描述】:
如何使用 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
【问题讨论】:
-
你说你需要像
12:02:34.323232这样的输出。当然,这意味着您需要以微秒为单位的时间(有 6 个小数位 - 毫秒只有 3 个小数位)。
标签: c++ time c++17 chrono milliseconds