将格林尼治标准时间转换为时代 [英] Converting GMT time to Epoch

查看:54
本文介绍了将格林尼治标准时间转换为时代的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将GMT时间转换为unix EPOCH时间非常麻烦.

I'm having much trouble converting a GMT time to a unix EPOCH time.

问题似乎与mktime有关.我当前的时区是+13小时.我认为这是问题所在,mktime假定为本地时间,并且在计算纪元时返回的值比实际GMT时间晚约12小时.

The problem seems to relate to mktime. My current timezone is +13 hrs ahead. I think this is the issue, mktime assumes localtime and when it calculates an epoch is returning a value that is about 12hrs before what the real GMT time is.

这是我的代码.

time_t t;
struct tm tm;
strptime(s, "%Y-%m-%dT%H:%M:%SZ", &tm);
tm.tm_isdst = -1; // -1 tells mktime figure it out
t = mktime(&tm);

当s ="2018-01-19T03:35:12Z"时,计算出的纪元为1516286112而不是应该提前约12小时的时间.

When s = "2018-01-19T03:35:12Z", it's computing the epoch to be 1516286112 Instead of an epoch which should be about 12hrs ahead.

在BIOS时钟设置为GMT的系统上,不会发生此错误.所以我只能得出结论,在这种情况下,mktime会按预期工作.

On a system where the BIOS clock is set to GMT, this error does not occur. So I can only conclude that mktime is working as expected when that situation is true.

偶然地,该字符串来自nosql服务器,该服务器在文档上显示正确的时间.我正在抓取当前纪元,并将其与文档中的解析日期进行比较并计算差异.这就是所有的事情了!

Incidentally, the string is coming from a nosql server which is displaying the correct time on a document. I'm grabbing the current epoch and comparing it to the parsed date from the document and computing the difference. This is where it all goes haywire!

推荐答案

所以问题是 mktime 遵守本地时区.

So the issue is mktime is respecting the local timezone.

要修复此问题,请使用 timegm (如果可用).或者从这个答案中得出自己的结论.

To fix that use timegm where available. Or roll your own from this answer.

gmtime算法的最小实现?

这篇关于将格林尼治标准时间转换为时代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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