在为以下问题编写示例代码后时区之间转换 https://stackoverflow.com/questions/1173578/converting-between-timezones-in-c,其中一条评论是需要更通用的方法来从时区 A 转换到时区 B。我自己也很好奇是否有一个更高级的原语来进行此类操作,所以我编写了下面的代码。
我发现的一个缺点是它不断地摆动环境变量中的 TZ,从而改变“本地时间”的概念。虽然它似乎有效(尽管我没有检查它对 DST 期间的反应,但由于它基于 Olson 数据库,大概应该如此),我很好奇是否有人对如何处理这个问题有更好的想法任务 ?
#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);
}