c – Linux上的距离UTC – LocalTime

我正在用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);
上一篇:MySQL和PHP中的时间戳比较(UT​​C,0000,时区)


下一篇:【六】Linux 7.6 中时间的设置