繁体   English   中英

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

[英]How to compare GMT time and local time in C?

我的服务器使用布拉格当地时间(+ 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
}

谢谢你的答案。

在带有 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 ,它表示自纪元以来经过的时间。 时区与这里无关。 一旦您将时间表示为相对于某个事件(即自纪元以来),然后将它们进行比较。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM