Joan Esteban Joan Esteban - 1 year ago 78
Linux Question

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

  • My first aproach was to check
    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!

Answer Source

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);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download