7

The time function in time.h gives milliseconds since the epoch.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278

5 Answers5

7

This is the precise way:

struct timeval tv;
int msec = -1;
if (gettimeofday(&tv, NULL) == 0)
{
    msec = ((tv.tv_sec % 86400) * 1000 + tv.tv_usec / 1000);
}

That will store into msec the number of milliseconds since midnight. (Or -1 if there was an error getting the time.)

Although it's usually a bad idea to store time-values in an int, I'm being a little cavalier and assuming int is at least 32-bit, and can easily accommodate the range (-1) to 86,400,000.

But I don't know if it's worth all the effort.

Shalom Craimer
  • 20,659
  • 8
  • 70
  • 106
  • 1
    There seems to be something wrong with your code, according to the C that I know. Maybe you should have declared `msec` beforehand, also used `else`. – Utkan Gezer Jul 20 '14 at 20:49
7

This is a simple way:

time_t seconds_since_midnight = time(NULL) % 86400;

To get approximate milliseconds since midnight, multiply seconds_since_midnight by 1000.

If you need more resolution (consider whether you really do), you will have to use another function such as gettimeofday().

Greg Hewgill
  • 951,095
  • 183
  • 1,149
  • 1,285
5

You use gettimeofday(2) which is defined in POSIX.1 and BSD.

It returns seconds and microseconds as defined in struct timeval from sys/time.h.

caskey
  • 12,305
  • 2
  • 26
  • 27
0

You will find C code examples for getting time and converting it to various formats here.

nik
  • 13,254
  • 3
  • 41
  • 57
0

Take a look at gmtime() Converts directly to Coordinated Universal Time (UTC)...

Vaibhav
  • 5,749
  • 3
  • 22
  • 18