c++ - 使用 mktime 计算时间不正确以获得 UTC+8

标签 c++ visual-studio-2012 ctime

我想获取香港时间(UTC+8),而我的本地时间是UTC-5。

在 VS2012 中使用并运行以下命令:

#pragma warning(disable : 4996)
char buffer[10];
time_t rawtime;
time(&rawtime);
strftime(buffer, 10, "%H:%M:%S", localtime(&rawtime));
cout << "LocalTime=" << buffer << endl;
strftime(buffer, 10, "%H:%M:%S", gmtime(&rawtime));
cout << "GMTime=" << buffer << endl;
tm* r = gmtime(&rawtime);
r->tm_hour += 8; // Hong Kong time
mktime(r); // Normalize the struct
strftime(buffer, 10, "%H:%M:%S", r);
cout << "HongKongTime=" << buffer << endl;

产生以下输出:

LocalTime=22:51:47
GMTime=02:51:47
HongKongTime=11:51:47

所以它正确地计算了 UTC,但是加上 8 小时实际上产生了 UTC +9 的时间。出了什么问题?

有没有比这种拼凑更优雅/更可靠的获取 UTC+8 的方法?

最佳答案

在将 TZ 环境变量更改为所需时区后,您可以使用 localtime:

#include <iostream>
#include <stdlib.h>
#include <time.h>

int main(){

    _putenv_s( "TZ", "GMT-08:00" );

    time_t mytime = time( NULL );
    struct tm* mytm = localtime( &mytime );

    std::cout << "Current local time and date: " << asctime(mytm);
    return 0;
}

对象 mytime 将作为函数 time() 的结果接收自 00:00 1970 年 1 月 1 日 UTC,这是当前的 Unix 时间戳。 localtime() 将使用 mytime 指向的值来填充一个 tm 结构,其中包含代表相应时间的值,以本地时区表示.

默认情况下,localtime() 使用的时区通常是您计算机中使用的时区。但是,您可以使用函数 _putenv_s() 更改它,我在其中操作了 TZ 变量并为其添加了一个新定义 GMT-08:00 这是香港的时区。

In POSIX systems, a user can specify the time zone by means of the TZ environment variable.

请注意,操作 TZ 变量的更标准方法是使用函数 int setenv (const char *name, const char *value, int replace) 但是它未在此示例中定义,因此我使用了替代方法。

您可以阅读更多关于 TZ 环境变量的信息 here

关于c++ - 使用 mktime 计算时间不正确以获得 UTC+8,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31175006/

相关文章:

c++ - 如何检查 cmd 中是否显示编译器错误?

visual-studio-2012 - Visual Studio 2012 未记录警告 C4447

python - 如何使用 Python 设置文件的 ctime?

c - 为什么 C struct tm (time.h) 返回错误的月份?

c++ - 是否有 gcc 的 __attribute__ (纯)的可移植等效项?

c++ - Qt 中的子目录模板

c++ - 如何使循环考虑多次出现?

xaml - 如何在 Windows 8 中的 Metro 应用程序中创建菜单项

installation - Visual Studio 2012 帮助查看器坏了,如何重新安装?

c - 使用ctime获取2个操作之间的间隔?