gpt4 book ai didi

c# - ConvertTimeToUtc 异常

转载 作者:行者123 更新时间:2023-11-30 17:21:33 24 4
gpt4 key购买 nike

您好,我在将本地时间转换为 UTC 时出现异常。我运行我的应用程序在设置了“俄罗斯标准时间”的 Windows 上。

public Convert()
{
DateTime dt = DateTime.Now;
DateTime dt1 = DateTime.Now;

// this converstion works
TimeZoneInfo.ConvertTimeToUtc(dt, TimeZoneInfo.Local);

// now let's get local timezone by id
TimeZoneInfo tz = TimeZoneInfo.FindSystemTimeZoneById("Russian Standard Time");

if (TimeZoneInfo.Local.Id == tz.Id)
{
// this is just to make sure we have the same timezones
}

// this conversion does not work
// throws exception System.ArgumentException
TimeZoneInfo.ConvertTimeToUtc(dt1, tz);

}

更新

异常文本说 - 无法完成转换,因为日期时间的 Kind 属性是错的。例如,如果 Kind 为 Local,则时区的值必须为 TimeZoneInfo.Local。

抱歉,这不是复制粘贴 - 原始消息不是英文的。

最佳答案

TimeZoneInfo.Equals 方法不仅在 Id 上进行比较:它还测试两个时区是否具有相同的调整规则 (TimeZoneInfo.HasSameRules) - 您可以使用 Reflector 查看这个。

我怀疑本地时区实际上使用的是夏令时,而 TimeZoneInfo.FindSystemTimeZoneById("Russian Standard Time") 返回的时区没有夏令时。

您应该能够使用调试器轻松检查这一点。

关于c# - ConvertTimeToUtc 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3280190/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com