我正在用 C++ 编写 Linux(Ubuntu 和 Debian Lenny)应用程序。
现在我需要知道 UTC 与过去某一天当前设置的系统时间之间的距离/偏移量。由于我需要转换记录的数据,因此需要根据过去的日期计算距离(该日期的 DST 设置可能与当天不同)。
有人知道怎么做吗?
编辑:阅读第一个答案我想我被误解了:我不想比较日期/时间。我有日期/时间值,我想将其从 UTC 转换为本地时间。
最佳答案
用日期准备 tm 结构:
struct tm date;
memset(&date,0,sizeof(date));
date.tm_year = year - 1900;
date.tm_mon = month - 1;
date.tm_mday = day;
date.tm_hour = hour;
date.tm_min = minute;
date.tm_sec = second;
date.tm_isdst = -1; // VERY IMPORTANT
mktime(&date); /// fill rest of fields
然后看看tm_gmtoff
printf("%d\n",date.tm_gmtoff);
这是与 UTC 的距离。
现在这是 Linux 和 BSD 特定的,它不会在其他系统上工作,但这个工作 关于夏令时。
阅读 man mktime 以获得更多信息。并用正确的值填充 struct tm
P.S.:从 UTC 转换为本地时间并返回?
time_t posix_time = timegm(&UTC_Filled_struct_tm); // Linux specific line
localtime_r(&posix_time,&local_Filled_struct_tm);
本地到 UTC
time_t posix_time = mktime(&local_Filled_struct_tm);
gmtime_r(&posix_time,&UTC_Filled_struct_tm);
关于c++ - 距离 UTC - Linux 上的本地时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4166706/