将当前时间从 Windows 转换为 C 或 C++ 中的 unix 时间戳 [英] Convert current time from windows to unix timestamp in C or C++

查看:42
本文介绍了将当前时间从 Windows 转换为 C 或 C++ 中的 unix 时间戳的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

First off, I know that this question was asked quite some times (although it seems that 90% are about converting Unix ts -> Windows). Secondly, I would add a comment to another accepted question where my problem would fit in instead of adding another one but I don't have enough reputation.

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

I saw the accepted solution in Convert Windows Filetime to second in Unix/Linux but am stuck at what I should pass to the function WindowsTickToUnixSeconds. Judging by the parameter name windowsTicks I tried GetTickCount but saw shortly after that this returns the ms since the system started but I need any reasonable count since the start of the Windows time (which seems to was in 1601?).

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

I saw that windows has a function for retrieving this time: GetSystemTime. I cannot pass the resulting struct to the proposed function in 1 as it is not a long long value.

难道有人不能在不忽略这些令人抓狂的细节的情况下为 C 或 C++ 提供一个完整的工作示例吗?

Can't someone please just give a full working example for C or C++ without omitting such mad-driving details?

推荐答案

也许我的问题措辞不好:我想要的只是获取 Windows 机器上的当前时间作为 unix 时间戳.我现在自己弄明白了(C 语言,Code::Blocks 12.11,Windows 7 64 位):

Maybe my question was phrased badly: All I wanted was to get the current time on a windows machine as a unix timestamp. I now figured it out myself (C language, Code::Blocks 12.11, Windows 7 64 bit):

#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

这篇关于将当前时间从 Windows 转换为 C 或 C++ 中的 unix 时间戳的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆