如何将两个字母的ISO-3166国家/地区代码映射到C#中的文化 [英] How to map a two letter ISO-3166 country code to a Culture in C#

查看:420
本文介绍了如何将两个字母的ISO-3166国家/地区代码映射到C#中的文化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要基于两个字母的ISO-3166国家/地区代码来本地化C#DateTime对象

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

我只能使用5个字符的国家/地区代表形式(en-US,nl-NL等)应用给定的文化。

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);

即使是整体式映射也是可以的(即,将多个国家/地区代码映射到单个C#文化)

Even a surjective mapping would be ok (i.e. more than one country code map to a single C# culture)

推荐答案

来自 CultureInfo(string)构造函数文档;

From CultureInfo(string) constructor documentation;


有关预定义区域性名称的列表,请参见 National Language
支持(NLS)API参考

也来自 CultureInfo.TwoLetterISOLanguageName 属性

Also from CultureInfo.TwoLetterISOLanguageName Property


ISO 639-1 两个字母的代码,用于显示当前CultureInfo的语言。

The ISO 639-1 two-letter code for the language of the current CultureInfo.

没有定义 US ,但是有 en (如果您真的必须使用两个字母名称),您可以使用它。

There is no US defined but there is en (if you really have to use two letter name) which you can use it. All of them defined in that standard.

var cultureInfo = new CultureInfo("en");

所有两个字母代码均有效,但 iv 用于 InvariantCulture ,所以我们可以忽略它。我写了一个简单的代码来检查它。

All of that two-letter codes are valid except iv which is for InvariantCulture so we can ignore it. I wrote a simple code to check it.

foreach (var culture in CultureInfo.GetCultures(CultureTypes.AllCultures))
{
     try
     {
          var c = new CultureInfo(culture.TwoLetterISOLanguageName);
     }
     catch (Exception)
     {
          Console.WriteLine(culture.TwoLetterISOLanguageName); // Only prints "iv"
     }
}

如何创建您的自己的映射?我建议执行以下步骤;

How to create your own mapping? I suggest to follow these steps;


  • 在ISO-3166和ISO 639-1标准中找到不同的两个字母的代码。

  • 创建自己的 KeyValuePair< string,string> 结构,其中包含第一个ISO-3166两个字母代码和第二个ISO 639-1两个字母代码

  • 如果您的两个字母的ISO-3166两个字母代码在此构造函数中失败,请检查它是否映射了两个字母的代码并尝试创建您的 CultureInfo 使用 that 两个字母的代码。

  • Find the different two-letter codes in ISO-3166 and ISO 639-1 standards.
  • Create your own 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.
  • If your two-letter ISO-3166 two-letter code fails in this constructor, check it's mapped two-letter code and try to create your CultureInfo using that two-letter code.

这篇关于如何将两个字母的ISO-3166国家/地区代码映射到C#中的文化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆