C program to print current time in hrs, mins , secs and
"Milliseconds"
Neelkanth_98$
cat time.c
#include
<stdio.h>
#include
<sys/time.h>
#include
<time.h>
#include
<math.h>
int
main() {
char buffer[26];
int millisec;
struct tm* tm_info;
struct timeval tv;
gettimeofday(&tv, NULL);
millisec = lrint(tv.tv_usec/1000.0); // Round to nearest millisec
if (millisec>=1000) { // Allow for rounding up to nearest second
millisec -=1000;
tv.tv_sec++;
}
tm_info = localtime(&tv.tv_sec);
strftime(buffer, 26, "%Y:%m:%d %H:%M:%S", tm_info);
printf("current Time: %s.%03d\n", buffer, millisec);
return 0;
}
Output
Neelkanth_98$
./a.out
current
Time: 2017:12:19 18:07:51.588
Neelkanth_98$ date
Tue
Dec 19 18:07:52 IST 2017