I need to localize my C# DateTime object based on a two letter ISO-3166 country code
https://en.wikipedia.org/wiki/ISO_3166-2
Is there a way to do it?
I'm only able to apply a given culture using the 5 character country representation (en-US, nl-NL and so on..)
System.Globalization.CultureInfo cultureinfo =
new System.Globalization.CultureInfo("nl-NL");
DateTime dt = DateTime.Parse(date, cultureinfo);
Even a surjective mapping would be ok (i.e. more than one country code map to a single C# culture)
The last part of CultureInfo.Name is country's ISO-3166 code, so this is how I ended up my solution,
The only problem is some countries have more than one culture like GB, so you can't select the right culture just with ISO-3166 code,
So
GetCultureFromTwoLetterCountryCode("GB")
will return"cy-GB"
culture which may be ok for Wales but not for Scotland.You can ignore these kind of exceptions or create your own cultureinfo database and store only one culture for each country. That will be the best solution.
I think you're confusing regions with cultures?
RegionInfo r = new RegionInfo("US");
MessageBox.Show(r.DisplayName);
This will return "United States"
From
CultureInfo(string)
constructor documentation;Also from
CultureInfo.TwoLetterISOLanguageName
PropertyThere is no
US
defined but there isen
(if you really have to use two letter name) which you can use it. All of them defined in that standard.All of that two-letter codes are valid except
iv
which is forInvariantCulture
so we can ignore it. I wrote a simple code to check it.How to create your own mapping? I suggest to follow these steps;
KeyValuePair<string, string>
structure which contains ISO-3166 two-letter codes as the first one and ISO 639-1 two-letter codes as the second one.CultureInfo
using that two-letter code.You should be able to use an invariant culture, if it's supported by .net.
E.g. This works:
As you've noted, there doesn't appear to be full support for all country codes, this is because the two characters it takes are a Neutral Culture.
You can get a list of all supported cultures via:
And specifically Neutral ones with:
The reason that
var culture = new CultureInfo("US");
doesn't work is because the neutral culture for US is EN. (the specific culture beingen-US
).There are other high voted answers on converting Country Codes to Cultures, which I'm not going to dupe here.