如何比较C中的GMT时间和当地时间?

问题描述 投票:0回答:1

我的服务器使用布拉格当地时间(+ 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 different time zones)
if (serverTime < userTime) {
    // to do
}

谢谢您的回答。

c time localtime mktime
1个回答
1
投票

在使用 glibc 的 linux 上,您只需使用

%Z
strptime
即可读取
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 different time zones)

但确实如此!

自事件发生以来已经过去的时间不能位于时区中。自纪元以来的秒数是自该事件以来已经过去的秒数,它是已经过去的相对时间,它是时间距离。无论您位于哪个时区,无论是否实行夏令时,每个地点自事件发生以来经过的时间都是相同的(嗯,不包括我们不关心的相对论效应)。时区无关紧要。

mktime
返回自纪元以来的秒数。
stat
返回
timespec
,表示自纪元以来经过的时间。时区在这里无关。一旦您将时间表示为相对于某个事件(即自纪元以来),然后就可以比较它们。

© www.soinside.com 2019 - 2024. All rights reserved.