应用偏移量时表示的异常 UTC 时间必须介于 0 年和 10,000 年之间。发生在某些计算机上
The exeption UTC time represented when the offset is applied must be between year 0 and 10,000. occurred in some computers
我在使用 C#
的 Windows 商店应用程序中有以下 code
:
birthDateTimePicker.Date = DateTime.Now;
if (birthDateTimePicker.Date == DateTime.MinValue)
{
no_date_lable.Visibility = Visibility.Collapsed;
birthDateTimePicker.Visibility = Visibility.Collapsed;
}
注意:这一行 birthDateTimePicker.Date = DateTime.Now;
是例如真正的用户选择或者来自服务器。
但是我在这一行中得到一个例外:
if (dt_born_dt == DateTime.MinValue)
抛出异常的原因是什么:
The UTC time represented when the offset is applied must be between
year 0 and 10,000.
真的,我在三台电脑上测试过这个,其中一台出现错误!!!
我将系统的时区更改为 (UTC-08:00
) 太平洋时间(美国和加拿大),但完全没有遇到此异常,而且代码工作正常!
我的问题真的是为什么这个异常发生在它的时区是(UTC+03:30
)德黑兰的系统中!
抱歉我的英语不好
所以您的控件 dt_born_dt
(请使用像 birthDateTimePicker
这样有意义的名称,并考虑到生日不需要时间而且肯定不能是第 1 年[没有人年龄 ~2015 现在还活着],也许使用可为 null 的类型)有一个类型为 DateTimeOffset
的 Date
属性,从调试器的 +3:30
值中可以看出显示。
现在这个类型有一个从 DateTime
的隐式转换,所以如果你这样做:
birthDatePicker.Date = DateTime.MinValue;
它将 DateTime.MinValue
转换为 UTC,它具有 DateTimeKind.Unspecified
类型。这将抛出您显示的异常,因为您处于 GMT+ 时区:它将从 MinValue
中减去您的 GMT 偏移量,产生无效值,如 Converting DateTime.MinValue to DateTimeOffset.[=26= 中所述]
解决方法:使用DateTimeOffset.MinValue
.
此外,不要在 Parse(Exact)
周围使用 try-catch
;使用 TryParse(Exact)
.
@CodeCaster 的回答非常完整且很有帮助。但是,解决此问题的另一种方法是将 "DateTime.MinValue" 转换为 UTC.
if (birthDateTimePicker.Date == DateTime.MinValue.ToUniversalTime())
我不得不使用这种方法,因为 "birthDateTimePicker.Date" 在我的数据库中输入的是 DateTime 而不是 DateTimeOffset,我不想转换它。
谢谢所有的朋友。
我在使用 C#
的 Windows 商店应用程序中有以下 code
:
birthDateTimePicker.Date = DateTime.Now;
if (birthDateTimePicker.Date == DateTime.MinValue)
{
no_date_lable.Visibility = Visibility.Collapsed;
birthDateTimePicker.Visibility = Visibility.Collapsed;
}
注意:这一行 birthDateTimePicker.Date = DateTime.Now;
是例如真正的用户选择或者来自服务器。
但是我在这一行中得到一个例外:
if (dt_born_dt == DateTime.MinValue)
抛出异常的原因是什么:
The UTC time represented when the offset is applied must be between year 0 and 10,000.
真的,我在三台电脑上测试过这个,其中一台出现错误!!!
我将系统的时区更改为 (UTC-08:00
) 太平洋时间(美国和加拿大),但完全没有遇到此异常,而且代码工作正常!
我的问题真的是为什么这个异常发生在它的时区是(UTC+03:30
)德黑兰的系统中!
抱歉我的英语不好
所以您的控件 dt_born_dt
(请使用像 birthDateTimePicker
这样有意义的名称,并考虑到生日不需要时间而且肯定不能是第 1 年[没有人年龄 ~2015 现在还活着],也许使用可为 null 的类型)有一个类型为 DateTimeOffset
的 Date
属性,从调试器的 +3:30
值中可以看出显示。
现在这个类型有一个从 DateTime
的隐式转换,所以如果你这样做:
birthDatePicker.Date = DateTime.MinValue;
它将 DateTime.MinValue
转换为 UTC,它具有 DateTimeKind.Unspecified
类型。这将抛出您显示的异常,因为您处于 GMT+ 时区:它将从 MinValue
中减去您的 GMT 偏移量,产生无效值,如 Converting DateTime.MinValue to DateTimeOffset.[=26= 中所述]
解决方法:使用DateTimeOffset.MinValue
.
此外,不要在 Parse(Exact)
周围使用 try-catch
;使用 TryParse(Exact)
.
@CodeCaster 的回答非常完整且很有帮助。但是,解决此问题的另一种方法是将 "DateTime.MinValue" 转换为 UTC.
if (birthDateTimePicker.Date == DateTime.MinValue.ToUniversalTime())
我不得不使用这种方法,因为 "birthDateTimePicker.Date" 在我的数据库中输入的是 DateTime 而不是 DateTimeOffset,我不想转换它。
谢谢所有的朋友。