【发布时间】: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(&time); // in GMT--> 不,那不是 GMT。mktime()假定&time指向描述当地时间的struct tm。 -
用
strptime()研究%Z和研究timegm()。 -
st_mtimespec.tv_sec; // +2 hours (Prague)你在本地得到stat输出?