获取当前时间(以毫秒为单位)或HH:MM:SS:MMM格式

Tin*_*a J 7 c++ date

我编写了一个c ++函数来获取HH:MM:SS格式化的当前时间.我如何添加毫秒或纳秒,所以我可以有一个像HH:MM:SS:MMM?如果不可能,以ms为单位返回当前时间的函数也会很好.然后我可以自己计算两个对数点之间的相对时间距离.

string get_time()
{
    time_t t = time(0);   // get time now
    struct tm * now = localtime(&t);
    std::stringstream sstm;
    sstm << (now->tm_hour) << ':' << (now->tm_min) << ':' << now->tm_sec;
    string s = sstm.str();
    return s;
}
Run Code Online (Sandbox Code Playgroud)

Gal*_*lik 16

这是一个使用C++11chrono库的便携方法:

#include <chrono>
#include <ctime>
#include <iomanip>
#include <sstream>
#include <string>

// ...

std::string time_in_HH_MM_SS_MMM()
{
    using namespace std::chrono;

    // get current time
    auto now = system_clock::now();

    // get number of milliseconds for the current second
    // (remainder after division into seconds)
    auto ms = duration_cast<milliseconds>(now.time_since_epoch()) % 1000;

    // convert to std::time_t in order to convert to std::tm (broken time)
    auto timer = system_clock::to_time_t(now);

    // convert to broken time
    std::tm bt = *std::localtime(&timer);

    std::ostringstream oss;

    oss << std::put_time(&bt, "%H:%M:%S"); // HH:MM:SS
    oss << '.' << std::setfill('0') << std::setw(3) << ms.count();

    return oss.str();
}
Run Code Online (Sandbox Code Playgroud)

  • 如果你像我一样被困在 GCC 4 上,只是一个警告:`std::put_time` 在 GCC 5 之前没有实现。 (2认同)

Den*_*met 5

这是使用 HowardHinnant日期库的更简洁的解决方案。

std::string get_time()
{
    using namespace std::chrono;
    auto now = time_point_cast<milliseconds>(system_clock::now());
    return date::format("%T", now);
}
Run Code Online (Sandbox Code Playgroud)