C/C++ : Get Current Time

Using Matlab, we can get the current date and time using “now” command.  Example, using Matlab  we can use below command :

>> datestr(now,'dd-mm-yyyy HH:MM:SS.FFF')
ans =
21-10-2014 13:41:58.666

How if we want to get current time using C/C++ with the result like Matlab ?

We can use “localtime” to get date and time in C/C++  and use gettimeofday to get time in milisecon. The complete code how to get current time in C/C++ is :

string now()
    time_t     now = time(0);
    struct tm  tstruct;
    char       buf[80];
    int        milli;   
    timeval    curTime;
    //get militime
    gettimeofday(&curTime, NULL);
    milli = curTime.tv_usec / 1000;
    //get localtime
    tstruct = *localtime(&now);
    // Visit http://en.cppreference.com/w/cpp/chrono/c/strftime
    // for more information about date/time format
    //construct time
    strftime(buf, sizeof(buf), "%Y/%m/%d %H:%M:%S", &tstruct);
    sprintf(buf, "%s.%03i", buf, milli);
    return buf;

int main(int argc, char **argv)
  string currT;
  currT = now();

  cout<<"CURRENT TIME ( yyyy/mm/dd HH:MM:SS.FFF ) = "<< currT << endl;

Compile the code using command :

g++ demo_now.cpp -lm -o demo_now

The sample running execution program is :

toto@ubuntu:~/Documents$ ./demo_now 
CURRENT TIME ( yyyy/mm/dd HH:MM:SS.FFF ) = 2014/10/21 13:53:07.069


Add a Comment

Your email address will not be published. Required fields are marked *