有没有一种简单的方法可以只创建美国时区的列表?我使用这个代码,但它产生每个时区,我只想要太平洋、中部、山区和东部的
public List<TimeZoneInfo> _timeZones = TimeZoneInfo.GetSystemTimeZones().ToList();
试着用消防水管喝水没有什么意义。只需明确要求:
var zones = new List<TimeZoneInfo> {
TimeZoneInfo.FindSystemTimeZoneById("Pacific Standard Time"),
TimeZoneInfo.FindSystemTimeZoneById("Mountain Standard Time"),
TimeZoneInfo.FindSystemTimeZoneById("Central Standard Time"),
TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time")
};
别忘了夏威夷和阿拉斯加:)
好吧,可以使用您描述的标准按ID过滤它们:
using System;
using System.Linq;
class Test
{
static void Main()
{
var inclusions = new[] { "Pacific", "Central", "Mountain", "Eastern" };
foreach (var zone in TimeZoneInfo.GetSystemTimeZones()
.Where(zone => inclusions.Any(x => zone.Id.Contains(x))))
{
Console.WriteLine(zone.Id);
}
}
}
然而,这得到了以下列表:
Pacific Standard Time (Mexico)
Pacific Standard Time
US Mountain Standard Time
Mountain Standard Time (Mexico)
Mountain Standard Time
Central America Standard Time
Central Standard Time
Central Standard Time (Mexico)
Canada Central Standard Time
SA Pacific Standard Time
Eastern Standard Time
US Eastern Standard Time
Central Brazilian Standard Time
Pacific SA Standard Time
SA Eastern Standard Time
Central Europe Standard Time
Central European Standard Time
W. Central Africa Standard Time
Central Asia Standard Time
N. Central Asia Standard Time
AUS Central Standard Time
AUS Eastern Standard Time
West Pacific Standard Time
Central Pacific Standard Time
这显然不是你想要的。
如果您只想要一组特定的时区,那么最好使用TimeZoneInfo.FindSystemTimeZoneById(id)
对所需时区的ID进行硬编码。
我创建了一个美国时区列表:
var zones = new List<TimeZoneInfo> {
TimeZoneInfo.FindSystemTimeZoneById("Pacific Standard Time"),
TimeZoneInfo.FindSystemTimeZoneById("Mountain Standard Time"),
TimeZoneInfo.FindSystemTimeZoneById("Central Standard Time"),
TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time"),
TimeZoneInfo.FindSystemTimeZoneById("US Eastern Standard Time"),
TimeZoneInfo.FindSystemTimeZoneById("US Mountain Standard Time"),
TimeZoneInfo.FindSystemTimeZoneById("Hawaiian Standard Time"),
TimeZoneInfo.FindSystemTimeZoneById("Alaskan Standard Time"),
};
我认为这是美国时区的更新列表:
var timezones = new List<TimeZoneInfo> {
TimeZoneInfo.FindSystemTimeZoneById("Pacific Standard Time"),
TimeZoneInfo.FindSystemTimeZoneById("Mountain Standard Time"),
TimeZoneInfo.FindSystemTimeZoneById("Central Standard Time"),
TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time"),
TimeZoneInfo.FindSystemTimeZoneById("US Eastern Standard Time"),
TimeZoneInfo.FindSystemTimeZoneById("US Mountain Standard Time"),
TimeZoneInfo.FindSystemTimeZoneById("Hawaiian Standard Time"),
TimeZoneInfo.FindSystemTimeZoneById("Alaskan Standard Time"),
TimeZoneInfo.FindSystemTimeZoneById("Pacific Standard Time (Mexico)"),
TimeZoneInfo.FindSystemTimeZoneById("Central Standard Time (Mexico)"),
TimeZoneInfo.FindSystemTimeZoneById("UTC")
};
这个怎么样?
var _timeZones = TimeZoneInfo.GetSystemTimeZones().ToList().Where(zone=>zone.DisplayName.Contains("US"));