问题描述
我的服务器使用布拉格当地时间(+ 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 上,您可以使用 %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 diferrent time zones)
但确实如此!
自事件起经过的时间不能在某个时区。自纪元以来的秒数是自该事件以来经过的秒数,它是经过的相对时间,它是时间上的距离。无论您在哪个时区,无论是否为夏令时,自事件以来经过的时间在每个位置都是相同的(好吧,不包括相对论效应,我们不关心)。时区无关紧要。 mktime
返回自纪元以来的秒数。 stat
返回 timespec
表示自纪元以来已经过去的时间。时区在这里无关。一旦您将时间表示为相对于某个事件(即自纪元以来),那么只需比较它们即可。