在C中的时区之间转换

时间:2009-07-23 18:19:51

标签: c timezone

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

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

提前致谢。

3 个答案:

答案 0 :(得分:5)

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

(已编辑以说明使用mktime规范化的其他方案)

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <sys/time.h>

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);
}

答案 1 :(得分:2)

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

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

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


编辑:

在回复评论时 - 您还可以让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 );

答案 2 :(得分:0)

很可能,您的操作系统为此提供了一些支持。

在unix派生中您可能希望查看asctime, asctime_r, ctime, ctime_r, difftime, gmtime, gmtime_r, localtime, localtime_r, mktime, timegm的手册页。