Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the time zone GMT offset in C

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?

like image 700
friedo Avatar asked Dec 10 '12 15:12

friedo


People also ask

How do I get timezone offset?

Definition and Usage. getTimezoneOffset() returns the difference between UTC time and local time. getTimezoneOffset() returns the difference in minutes. For example, if your time zone is GMT+2, -120 will be returned.

What is the offset for GMT?

Greenwich Mean Time (GMT) has no offset from Coordinated Universal Time (UTC). This time zone is in use during standard time in: Europe, Africa, North America, Antarctica.

What is Gmtime () function?

The gmtime() function converts the time in seconds since the Epoch pointed to by timer into a broken-down time, expressed as Coordinated Universal Time (UTC).

What is the difference between Mktime () and Gmtime ()?

The mktime subroutine returns the specified time in seconds encoded as a value of type time_t. If the time cannot be represented, the function returns the value (time_t)-1. The localtime and gmtime subroutines return a pointer to the struct tm.


2 Answers

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.

like image 134
alk Avatar answered Sep 21 '22 05:09

alk


How does localtime do it?

According to localtime man page

The localtime() function acts as if it called tzset(3) and sets the external variables tzname with information about the current timezone, timezone with the difference between Coordinated Universal Time (UTC) and local standard time in seconds

So you could either call localtime() and you will have the difference in timezone or call tzset():

extern long timezone;
....
tzset();
printf("%ld\n", timezone);

Note: if you choose to go with localtime_r() note that it is not required to set those variables you will need to call tzset() first to set timezone:

According to POSIX.1-2004, localtime() is required to behave as though tzset() was called, while localtime_r() does not have this requirement. For portable code tzset() should be called before localtime_r()

like image 27
iabdalkader Avatar answered Sep 19 '22 05:09

iabdalkader