【问题标题】:Get LocalTime of a different Time zone c++获取不同时区c ++的LocalTime
【发布时间】:2021-05-06 10:06:50
【问题描述】:

系统是UTC,有没有办法获取特定时区的本地时间?

大多数 windows api 的返回值基于系统时间。

如果有任何 api 可以传递时区指示并获取本地时间?

另外,阅读不同的api的windows提供,并认为这是一个:“EnumDynamicTimeZoneInformation

可能对我有用,但我无法让它运行,我看到一个未定义的标识符错误。 错误 C3861:“EnumDynamicTimeZoneInformation”:找不到标识符

在此链接中提到的包含 windows.h: https://docs.microsoft.com/en-us/windows/win32/api/timezoneapi/nf-timezoneapi-enumdynamictimezoneinformation?redirectedfrom=MSDN

在从上述 api 获取信息时,我可以尝试将其传递给:

SystemTimeToTzSpecificLocalTime

并希望这样做。 谁能建议我缺少什么。

在 VS2010 上试试这个

文件:time.cpp

#ifndef WINVER             
#define WINVER 0x0602      
#endif

#ifndef _WIN32_WINNT       
#define _WIN32_WINNT 0x0602
#endif

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

int main(){
    DYNAMIC_TIME_ZONE_INFORMATION d_tz;
    memset(&d_tz,0,sizeof(d_tz));
    DWORD res=0;
    res = EnumDynamicTimeZoneInformation(1, &d_tz);//fetch specific timezone info

    /*Use this next*/
    //SystemTimeToTzSpecificLocalTime();

    return 0;
}

【问题讨论】:

  • 您的目标 Windows 版本是什么? EnumDynamicTimeZoneInformation 仅从 Windows 8 开始支持。
  • Windows server2012。从链接可以看出支持这个版本
  • 你能粘贴一些你到目前为止尝试过的代码吗?
  • 您是否包含&lt;timezoneapi.h&gt; 标头?
  • 根据文档,EnumDynamicTimeZoneInformation 从 Windows 8 开始可用。要使其对编译器可见,您必须将最低目标版本设置为 _WIN32_WINNT_WIN8 (0x0602) .详情请见Using the Windows Headers

标签: c++ winapi timezone utc localtime


【解决方案1】:

综合cmets,下面的例子对我有用:

#define WINVER 0x0602         
#define _WIN32_WINNT 0x0602

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

int main() {
    DYNAMIC_TIME_ZONE_INFORMATION d_tz;
    memset(&d_tz, 0, sizeof(d_tz));
    DWORD res = 0;
    res = EnumDynamicTimeZoneInformation(1, &d_tz);//fetch specific timezone info

    /*Use this next*/
    SYSTEMTIME st = { 0 };
    SYSTEMTIME lt = { 0 };
    GetSystemTime(&st);
    SystemTimeToTzSpecificLocalTimeEx(&d_tz,&st, &lt);
    WCHAR time[250] = { 0 };

    GetTimeFormatEx(LOCALE_NAME_USER_DEFAULT, 0, &lt, L"HH':'mm':'ss tt", time, 250);
    std::wcout << L"Timezone: " << d_tz.TimeZoneKeyName << std::endl;
    std::wcout << lt.wYear << L"/" << lt.wMonth << L"/" << lt.wDay << L" " << time << std::endl;
    return 0;
}

使用EnumDynamicTimeZoneInformation 获取DYNAMIC_TIME_ZONE_INFORMATION 实例,然后将其与SYSTEMTIME 一起传递给SystemTimeToTzSpecificLocalTimeEx。最后得到具体的当地时间。

结果:

Timezone: Alaskan Standard Time
2021/2/2 17:25:39 PM

【讨论】:

  • 这对 2010 年有效吗?我正在寻找专门针对 vs2010 的。
  • @DrakeWu - 你的例子很好,但一般来说,应该使用TimeZoneKeyName 来识别时区。 StandardName 中的字符串是在 DST 生效时应用的本地化字符串(与 DaylightName 形成对比,DaylightName 是在 DST 时应用的本地化字符串有效)。
  • @Sash - 正如我在问题 cmets 中所问的那样 - 为什么 vs2010 已经过时而 vs2019 社区版是免费的?为什么要给自己制造不必要的痛苦?
  • @MattJohnson-Pint 感谢您的解释。
  • @MattJohnson-Pint 这是一个相当古老的项目,所以我坚持使用 vs2010,我明白你的意思,但相信我,我也不想经历这种痛苦。
猜你喜欢
  • 2012-12-12
  • 1970-01-01
  • 1970-01-01
  • 2015-03-29
  • 2020-07-11
  • 2016-04-30
  • 2023-03-30
  • 2021-01-16
  • 1970-01-01
相关资源
最近更新 更多