Get the time zone GMT offset in C

friedo picture friedo · Dec 10, 2012 · Viewed 45.1k times · Source

I'm using the standard mktime function to turn a struct tm into an epoch time value. The tm fields are populated locally, and I need to get the epoch time as GMT. tm has a gmtoff field to allow you to set the local GMT offset in seconds for just this purpose.

But I can't figure out how to get that information. Surely there must be a standard function somewhere that will return the offset? How does localtime do it?

Answer

alk picture alk · Dec 10, 2012

Just do the following:

#define _GNU_SOURCE /* for tm_gmtoff and tm_zone */

#include <stdio.h>
#include <time.h>

/* Checking errors returned by system calls was omitted for the sake of readability. */
int main(void)
{
  time_t t = time(NULL);
  struct tm lt = {0};

  localtime_r(&t, &lt);

  printf("Offset to GMT is %lds.\n", lt.tm_gmtoff);
  printf("The time zone is '%s'.\n", lt.tm_zone);

  return 0;
}

Note: The seconds since epoch returned by time() are measured as if in Greenwich.