Reputation: 1021
I'm doing some code where I need to known which time zone is active in the system (I'm working on a Linux SO):
My first aproach was to check TZ
enviroment var,it's empty unless I set it (for instance calling tzset)
After that I try extern long timezone
(time.h) but this variable is always 0.
Finally I calculate the difference of my timezone and UTC+0 but I don't get my real timezone because I don't known if daylight saving apply
I'm pretty sure that there are a easy (and most consistent) way to achieve this. I'm looking for something like "Europe/Paris" or "UTC+2" or something like that
Any help will be appreciated!
Upvotes: 4
Views: 1171
Reputation: 3519
Option 1)
timezone and tzname could be available after call tzset():
cout << "Before tzset: " << timezone << " " << tzname[0] << " " << tzname[1] << endl;
tzset();
cout << "After tzset: " << timezone << " " << tzname[0] << " " << tzname[1] << endl;
outputs (today, in Europe):
Before tzset: 0 GMT GMT
After tzset: -3600 CET CEST
Option 2) Some versions of "struct tm" (GNU, BSD, ...) contains fields "tm_zone" and "tm_isdst":
time_t timer;
struct tm *ptm;
timer = time(NULL);
ptm = localtime( &timer );
cout << ptm->tm_zone << " " << ptm->tm_isdst << endl;
timer -= 60*24*3600; // 60 days ago
ptm = localtime( &timer );
cout << ptm->tm_zone << " " << ptm->tm_isdst << endl;
outputs:
CET 0
CEST 1
Upvotes: 1
Reputation: 439
As a starting point, I would suggest this:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void)
{
char str[64];
time_t timer;
struct tm * ptm;
timer = time(NULL);
ptm = localtime(&timer);
strftime(str, sizeof(str), "%Z", ptm);
printf("TZ: %s\n", str);
return(0);
}
Upvotes: 3
Reputation: 76
The date +%Z
command shows the current timezone, but what you actually want is to set it correctly. First remove the current timezone file:
# rm -f /etc/localtime
Then set the correct one for your timezone:
# ln -s /usr/share/zoneinfo/<your-time-zone-here> /etc/localtime
Do an ls /usr/share/zoneinfo/
to see the available timezones. For me it's /usr/share/zoneinfo/Europe/Amsterdam
.
Then verify using the abovementioned date
command.
Upvotes: 0