17

I need to get milliseconds from the timer

    // get timer part
    time_t timer = time(NULL);
    struct tm now = *localtime( &timer );
    char timestamp[256];

    // format date time
    strftime(timestamp, sizeof(timestamp), "%Y-%m-%d_%H.%M.%S", &now);

I want to get like this in C#:

DateTime.Now.ToString("yyyy-MM-dd_HH.mm.ss.ff")

I tried using %f or %F but it does work with C++. how can I get %f for milliseconds from tm?

halfer
  • 19,824
  • 17
  • 99
  • 186
olidev
  • 20,058
  • 51
  • 133
  • 197
  • 4
    `time()` returns the **integer** number of seconds since the epoch. Thus obviously you cannot obtain subsecond precision by using it. Use `gettimeofday()` instead. – Hristo Iliev May 18 '12 at 14:16
  • Does this need to work on Windows only or is it cross-platform? – tinman May 18 '12 at 14:19
  • For unix, check out my borrowed [class](http://stackoverflow.com/questions/10608159/is-this-an-overflow/10608574#10608574) that I posted to another answer here on SO. You could disassemble it to just get the milliseconds. – Drise May 18 '12 at 16:08

8 Answers8

28
#include <chrono>

typedef std::chrono::system_clock Clock;

auto now = Clock::now();
auto seconds = std::chrono::time_point_cast<std::chrono::seconds>(now);
auto fraction = now - seconds;
time_t cnow = Clock::to_time_t(now);

Then you can print out the time_t with seconds precision and then print whatever the fraction represents. Could be milliseconds, microseconds, or something else. To specifically get milliseconds:

auto milliseconds = std::chrono::duration_cast<std::chrono::milliseconds>(fraction);
std::cout << milliseconds.count() << '\n';
bames53
  • 86,085
  • 15
  • 179
  • 244
7

there is the function getimeofday(). returns time in ms check here: http://souptonuts.sourceforge.net/code/gettimeofday.c.html

amanda
  • 394
  • 1
  • 9
  • 1
    The link is OK as of 2018-05-16. The code shown is badly defective. It consists of 4 headers and `int main(void) { char buffer[30]; struct timeval tv; time_t curtime; gettimeofday(&tv, NULL); curtime=tv.tv_sec; strftime(buffer,30,"%m-%d-%Y %T.",localtime(&curtime)); printf("%s%ld\n",buffer,tv.tv_usec); return 0; }` —— Using `%ld` to format microseconds (a) doesn't meet the question's goal of formatting milliseconds and (b) does not print microseconds accurately. When `tv_usec` holds 101 microseconds, it prints `.101` instead of `.000101`. — `printf("%s%.3ld\n", buffer, tv.tv_usec / 1000);` – Jonathan Leffler May 16 '18 at 14:42
6

On Windows using Win32 API SYSTEMTIME structure will give you milliseconds. Then, you should use Time Functions to get time. Like this:

#include <windows.h>

int main()
{
    SYSTEMTIME stime;
    //structure to store system time (in usual time format)
    FILETIME ltime;
    //structure to store local time (local time in 64 bits)
    FILETIME ftTimeStamp;
    char TimeStamp[256];//to store TimeStamp information
    GetSystemTimeAsFileTime(&ftTimeStamp); //Gets the current system time

    FileTimeToLocalFileTime (&ftTimeStamp,&ltime);//convert in local time and store in ltime
    FileTimeToSystemTime(&ltime,&stime);//convert in system time and store in stime

    sprintf(TimeStamp, "%d:%d:%d:%d, %d.%d.%d",stime.wHour,stime.wMinute,stime.wSecond, 
            stime.wMilliseconds, stime.wDay,stime.wMonth,stime.wYear);

    printf(TimeStamp);

    return 0;
} 
SChepurin
  • 1,814
  • 25
  • 17
6

Here is another c++11 answer:

#include <iostream>
#include <iomanip>
#include <chrono>
#ifdef WIN32
#define localtime_r(_Time, _Tm) localtime_s(_Tm, _Time)
#endif

int main()
{
    tm localTime;
    std::chrono::system_clock::time_point t = std::chrono::system_clock::now();
    time_t now = std::chrono::system_clock::to_time_t(t);
    localtime_r(&now, &localTime);

    const std::chrono::duration<double> tse = t.time_since_epoch();
    std::chrono::seconds::rep milliseconds = std::chrono::duration_cast<std::chrono::milliseconds>(tse).count() % 1000;

    std::cout << (1900 + localTime.tm_year) << '-'
        << std::setfill('0') << std::setw(2) << (localTime.tm_mon + 1) << '-'
        << std::setfill('0') << std::setw(2) << localTime.tm_mday << ' '
        << std::setfill('0') << std::setw(2) << localTime.tm_hour << ':'
        << std::setfill('0') << std::setw(2) << localTime.tm_min << ':'
        << std::setfill('0') << std::setw(2) << localTime.tm_sec << '.'
        << std::setfill('0') << std::setw(3) << milliseconds
        << std::endl;
}
Chris Desjardins
  • 2,631
  • 1
  • 23
  • 25
2

You can youse boost::posix_time::ptime class. Its reference there.

inkooboo
  • 2,904
  • 1
  • 19
  • 24
2

I, personally, use this one: http://wyw.dcweb.cn/time.htm

John Kaul
  • 340
  • 1
  • 5
1

under MS Visual Studio c/c++ include sys/timeb.h and use _ftime (_ftime_s). Retrieves a struct _timeb (_ftime64) containing the time_t struct and also milli seconds, see MSDN http://msdn.microsoft.com/en-/library/z54t9z5f.aspx

#include <sys/timeb.h>

struct _timeb timebuffer;
_ftime(&timebuffer);
timebuffer.millitm; //milli seconds
timebuffer.time; //the same like struct time_t
steven j
  • 11
  • 1
1

Try with this code:

struct tvTime;

gettimeofday(&tvTime, NULL);

int iTotal_seconds = tvTime.tv_sec;
struct tm *ptm = localtime((const time_t *) & iTotal_seconds);

int iHour = ptm->tm_hour;;
int iMinute = ptm->tm_min;
int iSecond = ptm->tm_sec;
int iMilliSec = tvTime.tv_usec / 1000;
int iMicroSec = tvTime.tv_usec;
Gustavo Morales
  • 2,614
  • 9
  • 29
  • 37
jeremy
  • 21
  • 2