将GMT转换为本地结果会产生一年的差异

时间:2016-06-12 21:30:00

标签: c timezone utc gmt

环境:Ubuntu 14.04。

我正试图存入GMT中指定的struct tm分解时间。这是我的C ++函数:

void mygmt(int year, int month, int day, int hour, int minute, int second) {
  struct tm gmtTime;

  memset(&gmtTime, 0, sizeof(struct tm));

  gmtTime.tm_mday = day;
  gmtTime.tm_mon = month - 1; // 0-based
  gmtTime.tm_year = year - 1900;
  gmtTime.tm_hour = hour;
  gmtTime.tm_min = minute;
  gmtTime.tm_sec = second;
  gmtTime.tm_zone = "GMT";

  char buffer [80];
  strftime (buffer,80,"GMT time:  %b %d, %G %I:%M:%S %p %Z.", &gmtTime);
  puts(buffer);  

  time_t rawtime = timegm(&gmtTime);
  struct tm* timeinfo = localtime (&rawtime);
  strftime (buffer,80,"Local time:  %b %d, %G %I:%M:%S %p %Z.",timeinfo);
  puts(buffer);
}

以下是我如何称呼它:

// June 11, 2016 23:34:03 (in GMT)
mygmt(2016, 6, 11, 23, 34, 3);

这是输出:

GMT time:  Jun 11, 2015 11:34:03 PM GMT.
Local time:  Jun 11, 2016 04:34:03 PM PDT.

我希望当地时间比格林威治标准时间早-7小时,而且那部分输出似乎是正确的。我感到困惑的是GMT时间的输出。它显示我与我指定的值相差一年。我如何解决它?

1 个答案:

答案 0 :(得分:2)

在致电strftime之前,请致电timegm填写tm - 字段设置为零:

// ...

time_t rawtime = timegm(&gmtTime);

char buffer [80];
strftime (buffer,80,"GMT time:  %b %d, %G %I:%M:%S %p %Z.", &gmtTime);
puts(buffer);

struct tm* timeinfo = localtime (&rawtime);
strftime (buffer,80,"Local time:  %b %d, %G %I:%M:%S %p %Z.",timeinfo);

// ...

注意:您可能会考虑%Y而不是%G(这有点复杂)。

另请参阅:std::mktime and timezone infoEasy way to convert a struct tm (expressed in UTC) to time_t type