Joan Esteban
Joan Esteban

Reputation: 1021

How to known which time zone the system is using

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

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

Answers (3)

pasaba por aqui
pasaba por aqui

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

Djee
Djee

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

sebvieira
sebvieira

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

Related Questions