Question

Is there any way to get milliseconds and its fraction part from 1970 using time.h in c language?

Was it helpful?

Solution

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).

OTHER TIPS

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 */
};

For Unix and Linux you could use gettimeofday.

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

    // the system time
    SYSTEMTIME systemTime;
    GetSystemTime( &systemTime );

    // the current file time
    FILETIME fileTime;
    SystemTimeToFileTime( &systemTime, &fileTime );

    // filetime in 100 nanosecond resolution
    ULONGLONG fileTimeNano100;
    fileTimeNano100 = (((ULONGLONG) fileTime.dwHighDateTime) << 32) + fileTime.dwLowDateTime;

    //to milliseconds and unix windows epoche offset removed
    ULONGLONG posixTime = fileTimeNano100/10000 - 11644473600000;
    return posixTime;

Unix time or Posix time is the time in seconds since the epoch you mentioned.

bzabhi's answer is correct: you simply multiply the Unix timestamp by 1000 to get milliseconds.

Be aware that all millisecond values returned by relying on the Unix timestamp will be multiples of 1000 (like 12345678000). The resolution is still only 1 second.

You can't get the fraction part

The comment from Pavel is correct also. The Unix timestamp does not take into account leap seconds. This makes it even less wise to rely on a conversion to milliseconds.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top