October 21, 2014
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;
return(0);
}
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
6 Comments
Nice post. I used to be checking continuously this blog and I am impressed!
Very useful info particularly the last section 🙂 I deal with
such information much. I was looking for this particular information for a very lengthy time.
Thanks and good luck.
Can you be more specific about the content of your article? After reading it, I still have some doubts. Hope you can help me. https://accounts.binance.bh/register/person?ref=QCGZMHR6
Write more, thats all I have to say. Literally, it seems as though you relied on the video to make your point.
You clearly know what youre talking about, why
throw away your intelligence on just posting videos to your blog when you could be giving us something enlightening to read?
Your point of view caught my eye and was very interesting. Thanks. I have a question for you.
ロボット エロfor theclouds were breaking away now,and Satan took the dog’s head in his lapand put the eye back in its place,
Can you be more specific about the content of your article? After reading it, I still have some doubts. Hope you can help me.