简体   繁体   中英

Read Timezoneinfo from windows registry (C++)

I am trying to read the TIME_ZONE_INFORMATION struct from windows registry with the following code:

void GetTimeZoneInfo(){
    TIME_ZONE_INFORMATION tz = {0}; 
    TIME_ZONE_INFORMATION tz_data={0};
    char *keyname="TZI";
    DWORD size = sizeof(tz_data);
    HKEY hk = NULL;
    char *zone_key = "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Time Zones\\Central Standard Time";
    if ((RegOpenKeyExA(HKEY_LOCAL_MACHINE, zone_key, 0, KEY_READ, &hk) == ERROR_SUCCESS))
    {
        if(RegQueryValueExA(hk, keyname, NULL, NULL, (LPBYTE) &tz_data, &size) == ERROR_SUCCESS)
        
        {    /*Control enters here*/
             /*Read the data*/
             cout<<"Successful in retrieving the value"<<endl;
            tz.Bias = tz_data.Bias;
            tz.DaylightBias = tz_data.DaylightBias;
            tz.DaylightDate = tz_data.DaylightDate;
            tz.StandardBias = tz_data.StandardBias;
            tz.StandardDate = tz_data.StandardDate;
        }
        else{ cout<<"Failure in retrieving the value"<<endl;}
    }
    else { cout<<"RegOpenKey Failure!"<<endl;}
}

It sets all to zero value, but don't see any error on running RegOpenKeyExA and RegQueryValueExA. TIME_ZONE_INFORMATION is stored in registry as type: REG_BINARY

Is this the right way to read from registry?

According to MS docs TZI key contains the following time zone information:

typedef struct _REG_TZI_FORMAT
{
    LONG Bias;
    LONG StandardBias;
    LONG DaylightBias;
    SYSTEMTIME StandardDate;
    SYSTEMTIME DaylightDate;
} REG_TZI_FORMAT;

You are reading to a wrong struct - TIME_ZONE_INFORMATION.

A couple of things:

  • In most cases you should be using the DYNAMIC_TIME_ZONE_INFORMATION structure, as it supports the full range of data that is in the registry. Most of the Win32 time zone functions have alternative versions that work with the dynamic structures.

  • You don't need to load the information from the registry yourself. Instead, use EnumDynamicTimeZoneInformation . Enumerate them until the TimeZoneKeyName matches the one you are looking for.

  • As nevilad pointed out , the TZI entries in the registry data aligns with _REG_TZI_FORMAT , which is slightly different than TIME_ZONE_INFORMATION structure. (But again, you don't need to read from the registry yourself. )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM