How can i get UTCTime in millisecond since January 1, 1970 in c language

For Unix and Linux you could use gettimeofday.

For Win32 you could use GetSystemTimeAsFileTime and then convert it to time_t + milliseconds:

void FileTimeToUnixTime(FILETIME ft, time_t* t, int* ms)
{
  LONGLONG ll = ft.dwLowDateTime | (static_cast<LONGLONG>(ft.dwHighDateTime) << 32);
  ll -= 116444736000000000;
  *ms = (ll % 10000000) / 10000;
  ll /= 10000000;
  *t = static_cast<time_t>(ll);
}

If you want millisecond resolution, you can use gettimeofday() in Posix. For a Windows implementation see gettimeofday function for windows.

#include <sys/time.h>

...

struct timeval tp;
gettimeofday(&tp);
long int ms = tp.tv_sec * 1000 + tp.tv_usec / 1000;

It's not standard C, but gettimeofday() is present in both SysV and BSD derived systems, and is in POSIX. It returns the time since the epoch in a struct timeval:

struct timeval {
    time_t      tv_sec;     /* seconds */
    suseconds_t tv_usec;    /* microseconds */
};

This works on Ubuntu Linux:

#include <sys/time.h>

...

struct timeval tv;

gettimeofday(&tv, NULL);

unsigned long long millisecondsSinceEpoch =
    (unsigned long long)(tv.tv_sec) * 1000 +
    (unsigned long long)(tv.tv_usec) / 1000;

printf("%llu\n", millisecondsSinceEpoch);

At the time of this writing, the printf() above is giving me 1338850197035. You can do a sanity check at the TimestampConvert.com website where you can enter the value to get back the equivalent human-readable time (albeit without millisecond precision).

Tags:

C

Time.H