首先,我知道这个问题被问了很多次(尽管似乎90%是关于转换Unix ts->Windows)。其次,我会在另一个公认的问题上添加一条评论,我的问题会适合这个问题,而不是添加另一个,但我没有足够的声誉。
我在Unix/Linux中的"将Windows文件时间转换为秒"中看到了公认的解决方案,但我不知道应该传递给函数WindowsTickToUnixSeconds。根据参数名称windowsTicks判断,我尝试了GetTickCount,但不久之后,它返回了自系统启动以来的ms,但我需要自Windows时间启动以来的任何合理计数(似乎是在1601?)。
我看到windows有一个检索时间的函数:GetSystemTime。我无法将生成的结构传递给1中建议的函数,因为它不是一个长值。
难道有人不能给出一个完整的C或C++的工作示例而不省略这些疯狂的驱动细节吗?
对于Windows上的用户:
Int64 GetSystemTimeAsUnixTime()
{
//Get the number of seconds since January 1, 1970 12:00am UTC
//Code released into public domain; no attribution required.
const Int64 UNIX_TIME_START = 0x019DB1DED53E8000; //January 1, 1970 (start of Unix epoch) in "ticks"
const Int64 TICKS_PER_SECOND = 10000000; //a tick is 100ns
FILETIME ft;
GetSystemTimeAsFileTime(out ft); //returns ticks in UTC
//Copy the low and high parts of FILETIME into a LARGE_INTEGER
//This is so we can access the full 64-bits as an Int64 without causing an alignment fault
LARGE_INTEGER li;
li.LowPart = ft.dwLowDateTime;
li.HighPart = ft.dwHighDateTime;
//Convert ticks since 1/1/1970 into seconds
return (li.QuadPart - UNIX_TIME_START) / TICKS_PER_SECOND;
}
函数的名称与其他Windows函数使用的命名方案相匹配。Windows系统时间定义为UTC。
函数 | 返回类型 | 分辨率 |
---|---|---|
GetSystemTimeAsFileTime | FILETIME结构 | 0.0000001秒 |
GetSystemTime | SYSTEMTIME结构 | 0.001秒 |
GetSystemTimeAsUnixTime | Int64 | 1秒 |
也许我的问题措辞不正确:我只想在windows机器上获得当前时间作为unix时间戳。我现在自己想明白了(C语言,代码::Blocks 12.11,Windows 7 64位):
#include <stdio.h>
#include <time.h>
int main(int argc, char** argv) {
time_t ltime;
time(<ime);
printf("Current local time as unix timestamp: %lin", ltime);
struct tm* timeinfo = gmtime(<ime); /* Convert to UTC */
ltime = mktime(timeinfo); /* Store as unix timestamp */
printf("Current UTC time as unix timestamp: %lin", ltime);
return 0;
}
示例输出:
Current local time as unix timestamp: 1386334692
Current UTC time as unix timestamp: 1386331092
使用GetSystemTime
设置的SYSTEMTIME
结构,可以很容易地创建一个struct tm
(有关结构的参考,请参见asctime
),并使用mktime
函数将其转换为"UNIX时间戳"。