4

I can printout time in UTC and local time like this:

  time_t now;
  struct tm  ts, tm;
  char buf[80];
  now = time(NULL);
  ts = *gmtime(&now);
  tm = *localtime(&now);
  strftime(buf, sizeof(buf), "%a %Y-%m-%d %H:%M:%S %Z", &ts);
  printf("%s\n", buf);
  strftime(buf, sizeof(buf), "%a %Y-%m-%d %H:%M:%S %Z", &tm);
  printf("%s\n", buf);

But how do I printout time in a specified timezone that is different than UTC or my current timezone? Also, would it be OS/distro dependent?

  • 2
    Not by "pure C". Pretty sure that it is possible with POSIX (see [here](http://stackoverflow.com/questions/8824156/c-localtime-when-changing-timezone)), which means that it is OS-dependent. – Grzegorz Szpetkowski Jan 25 '15 at 21:35
  • Thanks for the nuance. It seems I can use the provided answer for my case but it is good to know its limitations. – user4482856 Jan 25 '15 at 21:42

1 Answers1

2

You can use the approach documented here How can I set the time zone before calling strftime?, so use setenv and tzset before calling strftime:

setenv("TZ", "PST8PDT", 1);
tzset();
mtt = time(NULL);
mt = localtime(&mtt);
strftime(ftime,sizeof(ftime),"%Z %H%M",mt);
Community
  • 1
  • 1
Hans Z.
  • 50,496
  • 12
  • 102
  • 115