c++ - 在 C++17 中获取以毫秒为单位的时间?

标签 c++ time c++17 c++-chrono milliseconds

如何使用 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(&currentDateTimeTimeT);

    char currentDateTimeArrStr[100];
    std::strftime(currentDateTimeArrStr, 100, "%Y%m%d_%H%M%S.%f", &currentDateTimeLocalTime);

    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(&currentDateTimeLocalTime, "%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/

相关文章:

excel - 如何在 Excel 中创建时间范围图

c++ - 在 [现代] C++ 中通过 N 个变量进行范围/循环

c++ - 在点云库 (PCL) 中的超体素聚类过程中保留自定义字段

c++ - std::exp 给出与复数的 MATLAB exp 不同的结果

C++ 错误数组和结构

java - 如何在Java中获取时间分隔符?

date - 如何在Dart/Flutter中获取当前时间的GMT时间偏移值

c++ - DLL 不会在生成后事件中复制

C++ - 来自 std::string 的意外输出

c++ - 结构化绑定(bind)和基于范围的;在 gcc 中抑制未使用的警告