16

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:MMM? If not possible, a function that returns current time in ms would also be good. I can then calculate the relative time distances between two log points myself.

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;
}
3
  • 1
    std::put_time has %T for HH:MM:SS.
    – chris
    Jul 10, 2014 at 21:54
  • '... add milliseconds or nanoseconds ...' Huh! That's a big dimension range! Pick one :P ... Jul 10, 2014 at 21:56
  • Well, since I have a ping client, and on bash shell we only can access ns! :)
    – Tina J
    Jul 10, 2014 at 23:26

4 Answers 4

58

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();
}
5
  • 1
    Really? You get 3 digits of milliseconds? Feb 2, 2016 at 15:50
  • This solution is almost portable. However, not every OS supports every conversion specifier. On my Windows 7 machine I get the error "Invalid parameter passed to C runtime function." when trying to use specifiers like %F and %T. I had to replace them with %Y-%m-%d and %H:%M:%S, respectively. Aug 15, 2018 at 14:12
  • @Sebastian It should be portable between C++11 compliant compilers. Is your compiler fairly old? Maybe it has an incomplete C++11 implementation? I made the change in the code so it will work for more people, thanks for pointing it out.
    – Galik
    Aug 15, 2018 at 16:29
  • The compiler is new: $ g++ --version g++.exe (i686-posix-dwarf-rev0, Built by MinGW-W64 project) 8.1.0 It's the runtime that's causing the problems. If I have time I'll look into it more, but for now it's working for me without the aggregate format code like %F and %T. Aug 16, 2018 at 6:16
  • 2
    Just a warning if you are stuck on GCC 4 like I am: std::put_time wasn't implemented before GCC 5.
    – hansfn
    Mar 30, 2022 at 14:19
7

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);
}
2

For windows maybe:

#include <iostream>
#include <Windows.h>
#include <strsafe.h>

int main()
{
    CHAR sysTimeStr[13] = {};
    SYSTEMTIME systemTime;
    GetLocalTime(&systemTime);
    sprintf_s(sysTimeStr,
        "%u:%02u:%02u:%03u",
        systemTime.wHour,
        systemTime.wMinute,
        systemTime.wSecond,
        systemTime.wMilliseconds);

    std::cout << sysTimeStr;
}
1

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

2
  • 5
    Or use <chrono> in C++11.
    – chris
    Jul 10, 2014 at 22:01
  • 3
    Note that gettimeofday is a POSIX function and not standard C++. This solution is not portable to non-POSIX systems; in general, the C++11 approach from the other answer should be preferred.
    – Baum mit Augen
    Apr 28, 2018 at 17:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.