c# - 当 TimeZoneInfo.ConvertTimeToUtc 对于某些 DateTime 值时调用异常

标签 c# exception timezone

当我为这个特定的 dt 值运行代码时,当我调用 ConvertTimeToUtc 方法时抛出异常。 我的本地机器 timeZoneId 是“GMT 标准时间”

var tzi = TimeZoneInfo.FindSystemTimeZoneById("Central Standard Time");
var dt = new DateTime(1995, 4, 2, 2, 55, 0);
var t = TimeZoneInfo.ConvertTimeToUtc(dt, tzi);

异常(exception)情况是:

System.ArgumentException was unhandled
Message="The supplied DateTime represents an invalid time.  For example, when the clock is adjusted forward, any time in the period that is skipped is invalid.\r\nParameter 

最佳答案

是的,完全正确。 1995 年 4 月 4 日的中部标准时间凌晨 2:55 并不存在,因为挂钟 skipped from 2am to 3am due to daylight saving transitions .关于这一点,异常似乎相当清楚。 (这里使用“标准”有点棘手;将其称为“中央时间”更有意义,其中包括“中央标准时间”和“中央夏令时”,但这是另一回事。哎呀,我更喜欢Olson 标识符我自己...)

在其他时候,本地时间可能不明确 - 如果时钟倒退一个小时(或更多!),那么本地时间可能出现两次。

问题是:您希望您的代码在这种情况下如何表现?

有点不幸的是,异常只是 ArgumentException - 在 Noda Time 中我们将为这个确切的案例设置一个异常(exception),以便更容易发现和捕捉。 (我们还将提供类似 IsAmbiguous 和 IsSkipped 的东西,这样您就可以在不捕获异常的情况下进行检查。)

但基本信息是这不是 BCL 中的错误 - 这是故意的。

关于c# - 当 TimeZoneInfo.ConvertTimeToUtc 对于某些 DateTime 值时调用异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2416439/

相关文章:

java - 如何故意抛出错误来测试数据库回滚?

python - 如何捕获 str 异常?

linux - 在 dokku、OS 和 S3 之间设置时区

javascript - 在不明确询问用户的情况下收集用户时区的最佳方法是什么?

c# - 在 c# 中将网页捕获为图像,确保 javascript 呈现的元素可见

c# - CLR 如何找到实现 IDisposable 的类?

c# - IdentityServer4 - API 的用户权限

c# - 在 C# 9 记录上使用 "with"时忽略特定字段?

c# - 是否存在像 Thread.OnAborting() 这样的事件?

python - 如果时间戳 20160322T192202 不以 'Z' 结尾,那么 T 意味着什么?