Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
989 views
in Technique[技术] by (71.8m points)

c - Convert Unix/Linux time to Windows FILETIME

I am once again going from Windows to Linux, I have to port a function from Windows to Linux that calculates NTP time. Seems simple but the format is in Windows FILETIME format. I sort of have an idea what the differences are but so far I can not correctly convert my Linux time to the Windows FILETIME format. Does anyone have any ideas on how to do this?

I have seen some articles on how to do this but they all use Win32 functions and I can't use them! I can post the Windows code if this makes no sense.

They also take the current time and subtract it from January 1st 1900 to get the delta to find NTP, I would assume in Linux I just add the

const unsigned long EPOCH   = 2208988800UL

to my time to get this result?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The Microsoft documentation for the FILETIME structure explains what it is. The basic idea is that a Windows FILETIME counts by steps of 10-7 seconds (100-nanosecond intervals) from 1 Jan 1601 (why 1601? no idea...). In Linux you can obtain time in microseconds (10-6) from 1 Jan 1970 using gettimeofday(). Thus the following C function does the job:

#include <sys/time.h>
/**
 * number of seconds from 1 Jan. 1601 00:00 to 1 Jan 1970 00:00 UTC
 */
#define EPOCH_DIFF 11644473600LL

unsigned long long
getfiletime() {
    struct timeval tv;
    unsigned long long result = EPOCH_DIFF;
    gettimeofday(&tv, NULL);
    result += tv.tv_sec;
    result *= 10000000LL;
    result += tv.tv_usec * 10;
    return result;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...