3

How can we do this (get local time with milliseconds) without Boost? I have something like this:

time_of_day = time(NULL);

time_str_tm = localtime(&time_of_day);

printf("\n%02i:%02i:%02i\n", time_str_tm->tm_hour, time_str_tm->tm_min, time_str_tm->tm_sec);

but the tm structure has only seconds at last...

any suggestions?

Ksenia
  • 33
  • 1
  • 5

1 Answers1

3

You need gettimeofday(2)

struct timeval time_now;
gettimeofday(&time_now, NULL);
time_str_tm = gmtime(&time_now.tv_sec);

printf("\n%02i:%02i:%02i:%06i\n"
   , time_str_tm->tm_hour
   , time_str_tm->tm_min
   , time_str_tm->tm_sec
   , time_now.tv_usec);
Sergey L.
  • 21,822
  • 5
  • 49
  • 75
  • I had `gettimeofday` first, but I should avoid it for some reasons that my tutor can`t explain to me.. Is there any ways to avoid it? And do something with `localtime`? – Ksenia Feb 20 '14 at 11:05
  • @Ksenia No standard way that I am aware of. `gettimeofday` is standardised in both 4.3BSD and POSIX.1-2001, so I am sceptical why your tutor doesn't want you to use it. – Sergey L. Feb 20 '14 at 11:08
  • By the way, `tv_usec` is a microseconds not millisecinds.. Should I devide `tv_usec` by million? – Ksenia Feb 20 '14 at 11:11
  • @Ksenia Yes, just divide it by 1000 if you don't need the additional precision :) – Sergey L. Feb 20 '14 at 11:11
  • what is the difference between `localtime` and `gmtime`? – Ksenia Feb 20 '14 at 11:13
  • @Ksenia `localtime` gets the current time and returns a pointer to `struct tm`. `gmtime` converts a supplied `time_t` to a `struct tm`. Since there is a small delay between calling `gettimeofday` and `gmtime` it's better to reuse the result from `gettimeofday`. – Sergey L. Feb 20 '14 at 11:15
  • 1
    You`re much better than my tutor :) Thank you a lot! Your code works as I need to. – Ksenia Feb 20 '14 at 11:18