指定时区的打印输出时间

我可以打印出UTC时间和当地时间,如下所示:

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

但是如何在不同于UTC或当前时区的指定时区打印时间?还有OS /发行版依赖吗?

最佳答案 您可以使用此处记录的方法
How can I set the time zone before calling strftime?,因此在调用strftime之前使用setenv和tzset:

setenv("TZ", "PST8PDT", 1);
tzset();
mtt = time(NULL);
mt = localtime(&mtt);
strftime(ftime,sizeof(ftime),"%Z %H%M",mt);
点赞