Getting language and country

Is there a platform independent method for getting the system country and language of the currently running operating system?

If not, what about adding some methods for it?

This is for mac. You can look up this class

NSUserDefaults* defs = [NSUserDefaults standardUserDefaults];
NSArray* languages = [defs objectForKey:@"AppleLanguages"];
NSString* preferredLang = [languages objectAtIndex:0];

This returns “en”, for english. Haven’t got the check for country working yet.

Finally got the country code to work

NSUserDefaults* defs = [NSUserDefaults standardUserDefaults];
NSString* preferredLang = [defs objectForKey:@"Country"];

It returned

IN for India.

I will try to find code for windows.

Just an update on this. You could use these calls to access the information on Windows.

IMO it would be nice to have this functionality in the PlatformUtilities class. It’s one of the few places where my own code uses platform specific code.

It makes sense to have these calls in PlatformUtilities class. But that is something Jules has to decide.

I agree, I could definitely use this functionality in PlatformUtilities right about now…

GNU/Linux (glibc) uses the concept of Locales which uses environmental variables to affect localization for the system and individual programs. It is flexible in the sense that you can use different settings for different programs, and also use setlocale() to alter these settings at runtime. The normal case is of course to just use the system wide settings.

The simple way to find your language and country code is to query the environmental variable LANG, which in the english/India example might look like en_IN.UTF-8. The format is _., or more formally (quoting from man setlocale)

The c++ std library provides the “locale” class for this, which is available on every platform.

Unless I misunderstand, the locale class, as well as the C library locale functions, can only access attributes corresponding to the current locale. I couldn’t find anything in the libraries that would let you get or set the actual locale itself. I resorted to platform-specific methods. On Windows I ended up using GetUserDefaultUILanguage(), and on Mac, the CFLocale API.

…but the current locale is what you’re interested in, right?

The locale class delivers “C” on a Mac regardless of the user preferences. The only way to get at the preferred languages is through the Cocoa API.