C# 多语言环境下获取时区列表
如果不需要在A语言下获取B语言的时区列表,可以使用C#自带的
var systemZones = TimeZoneInfo.GetSystemTimeZones();
如果需要在A语言下获取B语言的时区列表,尝试过设置当前进程,线程的Culture是没办法实现的
var cultureInfo = new CultureInfo("en_US"); CultureInfo.CurrentCulture = cultureInfo; CultureInfo.CurrentUICulture = cultureInfo; Thread.CurrentThread.CurrentCulture = cultureInfo; Thread.CurrentThread.CurrentUICulture = cultureInfo; var systemZones = TimeZoneInfo.GetSystemTimeZones();
可以引入TimeZoneNames和TimerZoneConverter的Nuget包
var dictionary = TZNames.GetDisplayNames("en_US");
可以反射查看该Nuget的实现,实际上是引入了一个json的资源文件进行解析,如果把该资源文件拿出来自己进行获取
var filePath = @"Zones\TimeZoneNames.data.json"; var languageCode = "zh_CN"; languageCode = languageCode.Replace("-", "_"); if (!File.Exists(filePath)) return; using StreamReader file = File.OpenText(filePath); var jsonContent = file.ReadToEnd(); JObject jsonObject = JObject.Parse(jsonContent); var displayNames = jsonObject["DisplayNames"]; if (displayNames == null) return; var containsKey = ((JObject)displayNames).ContainsKey(languageCode); if (!containsKey) { if (!languageCode.Contains('_')) return; var code = languageCode.Split('_'); var containsCode = ((JObject)displayNames).ContainsKey(code[0]); if (!containsCode) return; languageCode = code[0]; } var jToken = displayNames[languageCode]; var jEnumerable = jToken.Children(); foreach (var child in jEnumerable) { if (child is JProperty property) { // 获取子元素的键和值 string key = property.Name; string val = property.Value.ToString(); } }