在C中的时区之间转换

我需要在C语言中转换时区之间的时间(在Linux上,所以任何特定的东西都会这样做)。

我知道我当前的时间,本地和UTC,我有目标时间的偏移量。 我试图使用mktime,gmtime,localtime和类似的function集,但仍然无法弄明白。

提前致谢。

由于评论不允许发布代码,因此单独发布答案。如果您知道“本地”时间和“UTC”时间,则可以计算“其他”时间与“本地”时间的偏移量。 然后将struct tm转换为日历时间,添加所需的秒数(作为目标时间的偏移量),并将其转换回struct tm:

(编辑以说明使用mktime标准化的另一个场景)

#include  #include  #include  #include  int main(int argc, char *argv) { struct timeval tv_utc; struct tm *local_tm, *other_tm; /* 'synthetic' time_t to convert to struct tm for the other time */ time_t other_t_synt; /* Other time is 1 hour ahead of local time */ int other_local_delta = 1*3600; /* the below two lines are just to set local_tm to something */ gettimeofday(&tv_utc, NULL); local_tm = localtime(&tv_utc.tv_sec); printf("Local time: %s", asctime(local_tm)); #ifdef DO_NOT_WRITE_TO_LOCAL_TM other_t_synt = mktime(local_tm) + other_local_delta; #else local_tm->tm_sec += other_local_delta; /* mktime will normalize the seconds to a correct calendar date */ other_t_synt = mktime(local_tm); #endif other_tm = localtime(&other_t_synt); printf("Other time: %s", asctime(other_tm)); exit(0); } 

如果您知道偏移量,可以使用gmtime()和tm结构直接设置它。

如果您知道当地时间和UTC,就会知道当地的偏移量。 如果您也知道目标偏移量,那么只需设置适当的tm_hour(如果你去<0或> 23,也可能翻转一天)。

有关示例代码,请参阅此gmtime参考页面 。 它显示基于偏移的关闭时区偏移。


编辑:

在回复评论时 – 您还可以让mktime为您处理转换,这样您就可以通过转换回time_t来简化此操作。 您可以使用以下内容:

 time_t currentTime; tm * ptm; time ( &currentTime ); ptm = gmtime ( &rawtime ); ptm->tm_hour += hours_to_shift; ptm->tm_minutes += minutes_to_shift; // Handle .5 hr timezones this way time_t shiftedTime = mktime( ptm ); // If you want to go back to a tm structure: tm * pShiftedTm = gmtime( &shiftedTime ); 

在所有可能的情况下,您的操作系统都会为此提供一些支持。

在unix派生的操作系统中,您可能需要查看asctime, asctime_r, ctime, ctime_r, difftime, gmtime, gmtime_r, localtime, localtime_r, mktime, timegm