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?
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.
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.
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).
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.
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, <);
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.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With