C 代码获取相对于 UTC 的本地时间偏移(以分钟为单位)?

标签 c time offset utc

我没有找到一种简单的方法来获取本地时间和 UTC 时间之间的时间偏移(以分钟为单位)。

起初我打算使用tzset(),但它不提供夏令时。根据手册页,如果夏令时有效,它只是一个不为零的整数。虽然通常是一个小时,但在某些国家/地区可能是半小时。

我宁愿避免计算 gmtime() 返回的当前 UTC 和 localtime() 之间的时差。

更通用的解决方案将为我提供指定位置的信息和正的 time_t 值,或者至少在本地。

编辑 1:用例是获取 https://github.com/chmike/timez 的正确本地时间偏移量。 。 顺便说一句,如果您认为 libc 函数可以操作时间,请阅读此文 https://rachelbythebay.com/w/2013/03/17/time/ .

编辑 2:迄今为止,我计算与 UTC 的时间偏移(以分钟为单位)的最佳和最简单的解决方案是

// Bogus: assumes DST is always one hour
tzset();
int offset = (int)(-timezone / 60 + (daylight ? 60 : 0));

问题是确定真正的夏令时。

编辑3:受到@trenki的答案的启发,我想出了以下解决方案。这是一个 hack,它欺骗 mktime()gmtime() 的输出视为本地时间。当 DST 更改位于 UTC 时间和本地时间之间的时间范围内时,结果不准确。

#include <stdio.h>
#include <time.h>

int main()
{
    time_t rawtime = time(NULL);
    struct tm *ptm = gmtime(&rawtime);
    // Request that mktime() looksup dst in timezone database
    ptm->tm_isdst = -1;                
    time_t gmt = mktime(ptm);
    double offset = difftime(rawtime, gmt) / 60;
    printf("%f\n", offset);
    return 0;
}

最佳答案

您系统的 strftime() 函数是否支持 %z%Z 说明符?在 FreeBSD 上,

 %Z    is replaced by the time zone name.

 %z    is replaced by the time zone offset from UTC; a leading plus sign
       stands for east of UTC, a minus sign for west of UTC, hours and
       minutes follow with two digits each and no delimiter between them
       (common form for RFC 822 date headers).

我可以用它来打印:

$ date +"%Z: %z"
CEST: +0200

ISO C99 在 7.23.3.5 strftime 函数中有这个:

%z     is replaced by the offset from UTC in the ISO 8601 format
       ‘‘−0430’’ (meaning 4 hours 30 minutes behind UTC, west of Greenwich),
       or by no characters if no time zone is determinable. [tm_isdst]
%Z     is replaced by the locale’s time zone name or abbreviation, or by no
       characters if no time zone is determinable. [tm_isdst]

关于C 代码获取相对于 UTC 的本地时间偏移(以分钟为单位)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55905815/

相关文章:

c - 在系统调用中获取 Cpu 和内存信息

c++ - 二叉树,其中每个节点的值保存子节点的总和

python - 在 Python 中,使用 win32api 没有设置正确的日期

javascript - 无法检索 ASP.NET 服务器端控件的偏移量

c - fgets 无限循环终止

c++ - 是一个堆栈指针伪随机数的良好来源

java - 如何获得自上次拆分以来的最后一次时间间隔?

indexing - Solr:同义词文件不应超过多大的大小?

php - 仅第三个变量中的非法字符串偏移

javascript - 使用路径点从顶部窗口偏移粘性 div