Amateur
Amateur

Reputation: 65

How to compare GMT time and local time in C?

my server uses local time of Prague (+ 2 hours) and visitor's request uses GMT time. In code I want to compare these times but for that I need to convert them to the same time zone. How to do it? When I try to use gmtime() and localtime() they returns same result.

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
}

Thank you for answer.

Upvotes: 0

Views: 445

Answers (1)

KamilCuk
KamilCuk

Reputation: 140880

On linux with glibc you can just use %Z with strptime to read 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)

But it is!

The time that has passed since an event can't be in a timezone. Count of seconds since epoch is how many seconds have passed since that event, it's relative time that has passed, it's distance in time. No matter in which timezone you are, no matter if daylight saving time or not, the time that has passed since an event is the same in every location (well, excluding relativistic effects, which we don't care about). Timezone is irrelevant. mktime returns the number of seconds since epoch. stat returns timespec which represents time that have passed since epoch. Timezone has nothing to do here. Once you represent time as relative to some event (ie. since epoch), then just compare them.

Upvotes: 1

Related Questions