【问题标题】:Convert current time from windows to unix timestamp in C or C++将当前时间从 Windows 转换为 C 或 C++ 中的 unix 时间戳
【发布时间】:2013-12-20 16:15:00
【问题描述】:

首先,我知道这个问题被问了很多次(尽管似乎 90% 是关于转换 Unix ts -> Windows)。 其次,我会在另一个已接受的问题中添加评论,而不是添加另一个问题,但我没有足够的声誉。

我在Convert Windows Filetime to second in Unix/Linux 中看到了公认的解决方案,但我被困在我应该传递给函数 WindowsTickToUnixSeconds 的内容上。从参数名称 windowsTicks 来看,我尝试了GetTickCount,但不久之后看到它返回 ms 自系统启动,但我需要自 启动以来的任何合理计数Windows 时代(似乎是在 1601 年?)。

我看到windows这次有一个检索函数:GetSystemTime。我无法将结果结构传递给 1 中的建议函数,因为它不是一个 long long 值。

难道不能给出一个完整的 C 或 C++ 工作示例而不省略这些疯狂的细节吗?

【问题讨论】:

标签: c++ c windows unix time


【解决方案1】:

对于 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。

Function Return type Resolution
GetSystemTimeAsFileTime FILETIME struct 0.0000001 s
GetSystemTime SYSTEMTIME struct 0.001 s
GetSystemTimeAsUnixTime Int64 1 s

【讨论】:

    【解决方案2】:

    也许我的问题措辞不当:我只想将 Windows 机器上的当前时间作为 unix 时间戳。 我现在自己弄清楚了(C 语言,Code::Blocks 12.11,Windows 7 64 位):

    #include <stdio.h>
    #include <time.h>
    int main(int argc, char** argv) {
        time_t ltime;
        time(&ltime);
        printf("Current local time as unix timestamp: %li\n", ltime);
    
        struct tm* timeinfo = gmtime(&ltime); /* Convert to UTC */
        ltime = mktime(timeinfo); /* Store as unix timestamp */
        printf("Current UTC time as unix timestamp: %li\n", ltime);
    
        return 0;
    }
    

    示例输出:

    Current local time as unix timestamp: 1386334692
    Current UTC time as unix timestamp: 1386331092
    

    【讨论】:

    • 在我的 win10 时间(&ltime) 上返回 GMT 时间,而不是本地时间。而且我不在 GMT 时区。
    【解决方案3】:

    使用GetSystemTime 设置的SYSTEMTIME 结构,很容易创建一个struct tm(请参阅asctime 以获取该结构的参考)并使用mktime 将其转换为“UNIX 时间戳”功能。

    【讨论】:

      猜你喜欢
      • 2019-04-24
      • 1970-01-01
      • 2012-02-03
      • 2010-11-03
      • 2014-03-07
      • 1970-01-01
      • 2023-03-18
      • 2013-04-07
      • 1970-01-01
      相关资源
      最近更新 更多