Get current time in milliseconds, or HH:MM:SS:MMM format

后端 未结 4 614
予麋鹿
予麋鹿 2020-12-01 18:54

I\'ve written a c++ function to get the current time in HH:MM:SS format. How can I add milliseconds or nanoseconds, so I can have a format like HH:MM:SS:M

相关标签:
4条回答
  • 2020-12-01 19:30

    Instead of using time() (seconds since the epoch), try gettimeofday(). Gives you a structure that includes a microseconds field.

    0 讨论(0)
  • 2020-12-01 19:33

    For windows maybe:

    #include <iostream>
    #include <Windows.h>
    #include <strsafe.h>
    
    int main()
    {
        CHAR sysTimeStr[13] = {};
        SYSTEMTIME systemTime;
        GetLocalTime(&systemTime);
        sprintf_s(sysTimeStr,
            "%u:%u:%u:%u",
            systemTime.wHour,
            systemTime.wMinute,
            systemTime.wSecond,
            systemTime.wMilliseconds);
    
        std::cout << sysTimeStr;
    }
    
    0 讨论(0)
  • 2020-12-01 19:43

    This is a portable method using the C++11 chrono library:

    #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();
    }
    
    0 讨论(0)
  • 2020-12-01 19:47

    This is a cleaner solution using HowardHinnant's date library.

    std::string get_time()
    {
        using namespace std::chrono;
        auto now = time_point_cast<milliseconds>(system_clock::now());
        return date::format("%T", now);
    }
    
    0 讨论(0)
提交回复
热议问题