繁体   English   中英

将当前时间从 Windows 转换为 C 或 C++ 中的 unix 时间戳

[英]Convert current time from windows to unix timestamp in C or C++

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

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

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

难道有人不能只为 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。

功能 返回类型 分辨率
获取系统时间作为文件时间 文件时间结构 0.0000001 秒
获取系统时间 系统时间结构 0.001 秒
GetSystemTimeAsUnixTime 64位 1 秒

也许我的问题措辞不好:我想要的只是将 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

使用GetSystemTime设置的SYSTEMTIME结构,可以轻松创建struct tm (请参阅asctime以获取该结构的参考)并使用mktime函数将其转换为“UNIX 时间戳”。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM