【问题标题】:TimeZone Not Found Exception [duplicate]时区未找到异常[重复]
【发布时间】:2016-04-25 10:59:07
【问题描述】:

我想将印度 DateTime 对象转换为东部 DateTime 对象。意味着我想更改特定 DateTime 对象的时区。为此,我编写了以下代码:

string easternZoneId = "Eastern Standard Time";
TimeZoneInfo easternZone = TimeZoneInfo.FindSystemTimeZoneById(easternZoneId);

string indianZoneId = "India Standard Time";
TimeZoneInfo indianZone = TimeZoneInfo.FindSystemTimeZoneById (indianZoneId);

DateTime d = TimeZoneInfo.ConvertTime (DateTime.Today, indianZone, easternZone);

当我尝试运行此语句时,控制台出现异常。

如何运行这段代码?我想把我的时间转换成东部时间。

编辑:现在我正在 Unity 编辑器中运行我的代码。我有 iMac 系统。 我想为 iPhone 设备运行这段代码。

【问题讨论】:

  • 真的确定你的系统在HKEY_LOCAL_MACHINE\Software\Microsoft\Windows NT\CurrentVersion\Time Zones的注册表键中有那些id吗?你有没有使用过GetSystemTimeZones 方法并检查结果?你的环境/平台是什么?
  • @SonerGönül,我没有使用 GetSystemTimeZones。我可以在 iPhone 设备上使用上述代码吗?
  • 也许你应该添加你正在使用 Mono 的平台。
  • 如果 DayTime.Today 在东部时区被调用,那么它将根据哪个时区返回数据?

标签: c# datetime timezone


【解决方案1】:

我的电脑上不存在“印度标准时间”。您可以列出您 PC 上所有支持的时区(我注意到在其他 PC 上可能会有所不同),如下所示:

var timeZones = TimeZoneInfo.GetSystemTimeZones(); 
foreach (TimeZoneInfo timeZone in timeZones)
{
    Console.WriteLine(timeZone.Id);
}

输出:

  • 日期标准时间
  • UTC-11
  • 夏威夷标准时间
  • ...

【讨论】:

  • 存在实际上是一个显示为(UTC+05:30) Chennai, Kolkata, Mumbai, New Delhi的时区。
【解决方案2】:

来自 msdn https://msdn.microsoft.com/en-us/library/system.timezoneinfo.findsystemtimezonebyid(v=vs.110).aspxenter link description here

FindSystemTimeZoneById 尝试将 id 与 Windows XP 和 Windows Vista 下注册表的 HKEY_LOCAL_MACHINE\Software\Microsoft\Windows NT\CurrentVersion\Time Zones 分支的子项名称匹配。此分支不一定包含时区标识符的完整列表。如果应用程序需要,您可以通过调用 CreateCustomTimeZone 方法的重载之一或通过调用 FromSerializedString 来反序列化表示所需时区的 TimeZoneInfo 对象来创建特定时区。但是,由这些方法调用创建的时区不包含在注册表中,并且无法使用 FindSystemTimeZoneById 方法进行检索。这些自定义时区只能通过 CreateCustomTimeZone 或 FromSerializedString 方法调用返回的对象引用来访问。

方法使用示例:

 // Get Tokyo Standard Time zone
      TimeZoneInfo tst = TimeZoneInfo.FindSystemTimeZoneById("Tokyo Standard Time");
      DateTime tstTime = TimeZoneInfo.ConvertTime(thisTime, TimeZoneInfo.Local, tst);      
      Console.WriteLine("Time in {0} zone: {1}", tst.IsDaylightSavingTime(tstTime) ?
                        tst.DaylightName : tst.StandardName, tstTime);
      Console.WriteLine("   UTC Time: {0}", TimeZoneInfo.ConvertTimeToUtc(tstTime, tst));

时区列表: https://en.wikipedia.org/wiki/List_of_tz_database_time_zones

只需找到您的时区 ID 并在示例中插入即可。

【讨论】:

  • 这不能回答问题,如果您从另一个链接复制某些内容,请至少给出一些归属。 stackexchange.com/legal
猜你喜欢
  • 2013-04-06
  • 2015-09-04
  • 1970-01-01
  • 1970-01-01
  • 2023-03-24
  • 2015-06-22
  • 2014-06-13
  • 2023-03-28
  • 2023-03-24
相关资源
最近更新 更多