22 12月 2009

[Windows] Local time 轉 UTC

Window提供了 API 可以轉換時間的時區。
  • TzSpecificLocalTimeToSystemTime:Local time -> UTC
  • SystemTimeToTzSpecificLocalTime :UTC -> Local time
第一個參數可指定 TIME_ZONE_INFORMATION,如果傳進 NULL 的話,即代表目前系統使用的Time Zone。

    SYSTEMTIME ConvertLocalTime2UTC(UINT year, UINT month, UINT day, UINT hour, UINT minute, UINT second)
    {
        SYSTEMTIME local, utc;
        ZeroMemory(&local, sizeof(local));
        local.wYear   = year;
        local.wMonth  = month;
        local.wDay    = day;
        local.wHour   = hour;
        local.wMinute = minute;
        local.wSecond = second;
        TzSpecificLocalTimeToSystemTime( NULL, &local, &utc );
        printf("UTC Time  =%d/%d/%d %d:%d:%d\n", utc.wYear, utc.wMonth, utc.wDay, utc.wHour, utc.wMinute, utc.wSecond);
        printf("Local Time=%d/%d/%d %d:%d:%d\n", local.wYear, local.wMonth, local.wDay, local.wHour, local.wMinute, local.wSecond);
        return utc;
    }
    
    SYSTEMTIME ConvertUTC2LocalTime(UINT year, UINT month, UINT day, UINT hour, UINT minute, UINT second)
    {
        SYSTEMTIME local, utc;
        ZeroMemory(&utc, sizeof(utc));
        utc.wYear   = year;
        utc.wMonth  = month;
        utc.wDay    = day;
        utc.wHour   = hour;
        utc.wMinute = minute;
        utc.wSecond = second;
        SystemTimeToTzSpecificLocalTime( NULL, &utc, &local );
        printf("UTC Time  =%d/%d/%d %d:%d:%d\n", utc.wYear, utc.wMonth, utc.wDay, utc.wHour, utc.wMinute, utc.wSecond);
        printf("Local Time=%d/%d/%d %d:%d:%d\n", local.wYear, local.wMonth, local.wDay, local.wHour, local.wMinute, local.wSecond);
        return local;
    }

    Reference:

    12 12月 2009

    [Win32 API] String Conversion

    在Windows底下做字串轉換其實還滿簡單的,在MFC的Library裡,提供了一些簡單的Marco可以用,就可以針對wstring, string, CComBSTR, BSTR之間做轉換了。需 Include AtlBase.h, AtlConv.h

    以下是 ATL7.0 版 Marco、Class的命名規則
    CSourceType2[C]DestinationType[EX]

    以下是 ATL3.0 舊版 Marco的命名規則
    SourceType2[C]DestinationType[EX]