views:

120

answers:

1

After writing a sample code for the question about converting between timezones, one of the comments to it was the need for more general method for converting from timezone A to timezone B. I was curious myself too to have a more high-level primitives for such a manipulations, so I wrote the below code.

One drawback I see is that it constantly wiggles the TZ in the environment variables, changing the notion of 'local time'. While it seems to work (though I did not check on how it react to the DST periods, but since it's based on the Olson database, presumably it should), I was curious if anyone might have some better ideas on how to deal with this task ?

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <sys/time.h>

time_t utc_now() {
  struct timeval tv_utc;
  gettimeofday(&tv_utc, NULL);
  return tv_utc.tv_sec;
}

void use_tz(char *timezone) {
  if(timezone) {
    setenv("TZ", timezone, 1);
  } else {
    unsetenv("TZ");
  }
  tzset();
}

time_t utc_from_local_tm(struct tm *local_tm, char *timezone) {
  time_t utc;
  use_tz(timezone);
  utc = mktime(local_tm);
  return utc;
}

struct tm *local_tm_from_utc(time_t utc, char *timezone) {
  use_tz(timezone);
  return localtime(&utc);
}

int main(int argc, char *argv[]) {
  struct tm *tm;
  struct tm tm2;
  time_t utc, utc2, utc3;
  utc = utc_now();
  tm = local_tm_from_utc(utc, "Europe/Brussels");
  printf("Local time in Brussels now: %s", asctime(tm));
  utc2 = utc_from_local_tm(tm, "Europe/Moscow");
  tm = local_tm_from_utc(utc2, "UTC");
  printf("UTC time if the above was the Moscow local time: %s", asctime(tm));

  memset(&tm2, sizeof(tm2), 0);
  /* 13:00:00 on 11 dec 2010 */
  tm2.tm_sec = tm2.tm_min = 0;
  tm2.tm_hour = 13;
  tm2.tm_mon = 11;
  tm2.tm_mday = 11;
  tm2.tm_year = 110;


  utc3 = utc_from_local_tm(&tm2, "Europe/Brussels");
  printf("Brussels time: %s", asctime(&tm2));
  tm = local_tm_from_utc(utc3, "Europe/Moscow");
  printf("At 13:00:00 on 11 dec 2010 CET the time in Moscow will be: %s", asctime(tm));

  exit(0);
}
+1  A: 

If storing the TZ information in an environment variable bugs you, then how about creating a new struct that contains both struct tm as well as a char* for the TZ information?

I am spoiled because R does these things quite well:

R> now <- Sys.time()
R> now
[1] "2009-08-01 17:19:07 CDT"
R> format(now, tz="Europe/Brussels")
[1] "2009-08-02 00:19:07"
R>

It has a few extension / replacements to the standard POSIX functions, see the file R-2.9.1/src/main/datetime.c (where R-2.9.1 is the current release)

Dirk Eddelbuettel
Ah, interesting. I'll take a look at R sources - I heard about R but did not look at it yet. Thanks! +1 :) The itchy feeling was mostly because potentially there would be other threads - so my naive code might behave buggy in the multithreaded environment.
Andrew Y
Finally had the time to look at it - awesome. Thanks for the reference, it does answer question fully.
Andrew Y