Delphi: get country codes by LocaleID

I need a way to get country code like “en” or “uk” or “jp” by locale ID:

  • English-US id is 1033 -> “en” (or “en-US”)
  • Japanese id is 1041 -> “jp”
  • etc

Like:

function GetCountryFromLoc(lcid: Integer): string;

I use Delphi 7.


2 Solutions
Solution

Add the data here into an object and access it by key name:
http://www.science.co.il/Language/Locale-codes.asp

Solution

Starting with Windows vista you can use the LCIDToLocaleName function.

Try this sample

{$APPTYPE CONSOLE}

uses
  Windows,
  SysUtils;

const
  LOCALE_NAME_MAX_LENGTH = 85;

function LCIDToLocaleName(Locale: LCID; lpName: LPWSTR; cchName: Integer;
  dwFlags: DWORD): Integer; stdcall;external kernel32 name 'LCIDToLocaleName';

var
   strNameBuffer : array [0..LOCALE_NAME_MAX_LENGTH-1] of WideChar;
begin
    if (LCIDToLocaleName(1033, strNameBuffer, LOCALE_NAME_MAX_LENGTH, 0) = 0) then
      RaiseLastOSError
    else
      Writeln(strNameBuffer);

    if (LCIDToLocaleName(1041, strNameBuffer, LOCALE_NAME_MAX_LENGTH, 0) = 0) then
      RaiseLastOSError
    else
      Writeln(strNameBuffer);

  Readln;
end.

On pre-Windows Vista systems you can use the DownlevelLCIDToLocaleName function.

This will return

en-US
ja-JP