-1

Environment: Ubuntu 14.04.

I am trying to store into struct tm broken down time specified in GMT. Here is my C++ function:

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

Here's how I am calling it:

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

And here's the output:

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

I expect local time to be -7 hours from GMT and that part of the output seems to be right. What I am confused about is the output for GMT time. It shows me a difference of one year from the value I specified. How do I fix it?

Box Box Box Box
  • 5,094
  • 10
  • 49
  • 67
Peter
  • 11,260
  • 14
  • 78
  • 155

1 Answers1

2

Before calling strftime, call timegm to fill tm-fields set to zero:

// ...

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

// ...

Note: You might consider %Y instead of %G (which is a bit complicated).

See also: std::mktime and timezone info and Easy way to convert a struct tm (expressed in UTC) to time_t type.

Community
  • 1
  • 1