gpt4 book ai didi

c - 在 C 中操纵时间(时区之间)的一般方法?

转载 作者:太空狗 更新时间:2023-10-29 15:41:29 26 4
gpt4 key购买 nike

在为关于 converting between timezones 的问题编写示例代码之后,对它的评论之一是需要更通用的方法来从时区 A 转换到时区 B。我自己也很好奇,想为这种操作提供更高级的原语,所以我编写了以下代码。

我看到的一个缺点是它会不断地在环境变量中摆动 TZ,从而改变“本地时间”的概念。虽然它似乎有效(尽管我没有检查它对 DST 期间的 react ,但由于它基于 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);
}

最佳答案

如果将 TZ 信息存储在环境变量中会让您感到厌烦,那么创建一个包含 struct tm 以及用于 TZ 信息的 char* 的新结构怎么样?

我被宠坏了因为R这些事情做得很好:

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>

它对标准 POSIX 函数有一些扩展/替换,请参阅文件 R-2.9.1/src/main/datetime.c(其中 R-2.9.1 是当前版本)

关于c - 在 C 中操纵时间(时区之间)的一般方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1217566/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com