c++windowsinternationalizationsystemtime

convert Windows SYSTEMTIME to a string or char buf in C++ with user's "Region and Language" format?


How does my C++ program convert a SYSTEMTIME in the user's preferred "long date format" either as defaulted from their Language setting, or as custom-set on the Control Panel->Region and Language dialog?

If it matters I'm on Visual Studio 2017 and primarily looking for C/C++03 type solutions but if there's a solution for newer C++ I wouldn't mind seeing it.


Solution

  • TIME_ZONE_INFORMATION tzi;
    if ( GetTimeZoneInformation( &tzi ) == TIME_ZONE_ID_INVALID )
    MyErrorFunction( "GetTimeZoneInformation() = TIME_ZONE_ID_INVALID : %s",
        GetLastErrorAsString().c_str() );
      :
      :
    
    SYSTEMTIME st, stLocal;
    BOOL bRV = FileTimeToSystemTime( ftLastAccessTime, &st );
    SystemTimeToTzSpecificLocalTime( &tzi, &st, &stLocal );
    
    GetDateFormat( LOCALE_USER_DEFAULT, DATE_LONGDATE, &stLocal,
                   NULL, szBuf, sizeof( szBuf ) );
    
    int iBufUsed = strlen( szBuf );
    if ( iBufUsed < sizeof( szBuf ) - 2 )
         szBuf[ iBufUsed++ ] = ' ';
    
    GetTimeFormat( LOCALE_USER_DEFAULT, 0, &stLocal,
                   NULL, szBuf + iBufUsed, sizeof( szBuf ) - iBufUsed );
    
    // szBuf holds Date and Time, in the user's timezone, formatted as the user prefers.