【问题标题】:How to compare GMT time and local time in C?如何在C中比较GMT时间和本地时间?
【发布时间】:2021-07-10 18:41:43
【问题描述】:

我的服务器使用布拉格当地时间(+ 2 小时),访问者的请求使用 GMT 时间。 在代码中我想比较这些时间,但为此我需要将它们转换为相同的时区。怎么做?当我尝试使用 gmtime() 和 localtime() 时,它们返回相同的结果。

struct tm   time;
struct stat data;
time_t userTime, serverTime;

// this time will send me user in GMT
strptime("Thu, 15 Apr 2021 17:20:21 GMT", "%a, %d %b %Y %X GMT", &time)
userTime = mktime(&time); // in GMT

// this time I will find in my server in another time zone
stat("test.txt", &data);
serverTime = data.st_mtimespec.tv_sec; // +2 hours (Prague)

// it's not possible to compare them (2 diferrent time zones)
if(serverTime < userTime) {
    // to do
}

谢谢你的回答。

【问题讨论】:

  • C 还是 C++?选择一个。
  • 您的代码中似乎没有使用gmtime()localtime()
  • userTime = mktime(&amp;time); // in GMT --> 不,那不是 GMT。 mktime() 假定 &amp;time 指向描述当地时间的 struct tm
  • strptime()研究%Z和研究timegm()
  • st_mtimespec.tv_sec; // +2 hours (Prague) 你在本地得到stat 输出?

标签: c time localtime mktime


【解决方案1】:

在带有 glibc 的 linux 上,您可以使用 %Zstrptime 来读取 GMT

#define _XOPEN_SOURCE
#define _DEFAULT_SOURCE
#include <time.h>
#include <assert.h>
#include <string.h>
#include <sys/stat.h>
#include <stdio.h>

int main() {
    // this time will send me user in GMT
    struct tm tm;
    char *buf = "Thu, 15 Apr 2021 17:20:21 GMT";
    char *r = strptime(buf, "%a, %d %b %Y %X %Z", &tm);
    assert(r == buf + strlen(buf));
    time_t userTime = timegm(&tm);

    // this time represents time that has passed since epochzone
    struct stat data;
    stat("test.txt", &data);
    // be portable, you need only seconds
    // see https://pubs.opengroup.org/onlinepubs/007904875/basedefs/sys/stat.h.html
    time_t serverTime = data.st_mtime;

    // it's surely is possible to compare them
    if (serverTime < userTime) {
        // ok
    }
}

// it's not possible to compare them (2 diferrent time zones)

但它是!

自事件不能处于时区以来经过的时间。自纪元以来的秒数是自​​该事件以来经过的秒数,它是经过的相对时间,是时间上的距离。无论您在哪个时区,无论是否采用夏令时,自事件发生以来经过的时间在每个位置都是相同的(嗯,不包括我们不关心的相对论效应)。时区无关紧要。 mktime 返回自纪元以来的秒数。 stat 返回 timespec,它表示自纪元以来经过的时间。时区与这里无关。一旦您将时间表示为相对于某个事件(即自纪元以来),然后只需比较它们即可。

【讨论】:

  • mktime(&amp;tm); 假定 struct tm 是本地时间,而不是像 strptime(buf, "%a, %d %b %Y %X %Z", &amp;tm); 那样填充使用 timegm() 代替。
猜你喜欢
  • 1970-01-01
  • 2011-10-07
  • 2013-01-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-20
  • 2014-04-17
  • 2013-10-29
相关资源
最近更新 更多