c++ - 距离 UTC - Linux 上的本地时间

标签 c++ c linux utc dst

我正在用 C++ 编写 Linux(Ubuntu 和 Debian Lenny)应用程序。

现在我需要知道 UTC 与过去某一天当前设置的系统时间之间的距离/偏移量。由于我需要转换记录的数据,因此需要根据过去的日期计算距离(该日期的 DST 设置可能与当天不同)。

有人知道怎么做吗?

编辑:阅读第一个答案我想我被误解了:我不想比较日期/时间。我有日期/时间值,我想将其从 UTC 转换为本地时间。

最佳答案

用日期准备 tm 结构:

struct tm date;
memset(&date,0,sizeof(date));
date.tm_year = year - 1900;
date.tm_mon = month - 1;
date.tm_mday = day;
date.tm_hour = hour;
date.tm_min = minute;
date.tm_sec = second;
date.tm_isdst = -1; // VERY IMPORTANT

mktime(&date); /// fill rest of fields

然后看看tm_gmtoff

printf("%d\n",date.tm_gmtoff);

这是与 UTC 的距离。

现在这是 Linux 和 BSD 特定的,它不会在其他系统上工作,但这个工作 关于夏令时。

阅读 man mktime 以获得更多信息。并用正确的值填充 struct tm

P.S.:从 UTC 转换为本地时间并返回?

time_t posix_time = timegm(&UTC_Filled_struct_tm); // Linux specific line
localtime_r(&posix_time,&local_Filled_struct_tm);

本地到 UTC

time_t posix_time = mktime(&local_Filled_struct_tm);
gmtime_r(&posix_time,&UTC_Filled_struct_tm);

关于c++ - 距离 UTC - Linux 上的本地时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4166706/

相关文章:

c++ - 用于编译和运行 C++ 的 bash 脚本

c++ - 不了解 C++11 类型推断

python - 如何从 GitLab 下载单个文件?

linux - 是否有一个 linux 命令来确定与给定进程 ID 关联的窗口 ID?

c++ - "just-in-time calculation"是否适合用于可变?

c++ - 可变参数模板迭代和 GCC

c - 没有得到下面的 C 代码中发生的事情

将特定数据从源缓冲区复制到多个目标缓冲区

C- 不正确的方法需要纠正

linux - 在 KDE 中,如何自动判断 Konsole 终端在哪个 "Desktop"中?