【问题标题】:How to solve timezone conversion error?如何解决时区转换错误?
【发布时间】:2016-06-23 09:08:46
【问题描述】:

我正在尝试使用此代码转换为瑞典时区:

Thread.CurrentThread.CurrentCulture = new CultureInfo("sv-SE");
TimeZoneInfo cet = TimeZoneInfo.FindSystemTimeZoneById("Central European Standard Time");
DateTime currentDate = DateTime.SpecifyKind(DateTime.Now, DateTimeKind.Local);


var swedishTime = TimeZoneInfo.ConvertTime(currentDate, cet, TimeZoneInfo.Local);

由于某种原因,我得到:

{"转换无法完成,因为提供的 DateTime 没有正确设置 Kind 属性。例如,当 Kind 属性为 DateTimeKind.Local,源时区必须为 TimeZoneInfo.Local。\r\n参数名称:sourceTimeZone"}

我错过了什么?

【问题讨论】:

  • 使用正确的类型,DateTimeOffset。单独使用DateTime 无法避免转换错误,即使它设置为DateTimeKind.UTC。例如本地 - 到什么? Web 应用程序、服务器还是浏览器?

标签: c# asp.net-mvc datetime timezone


【解决方案1】:

一些事情:

  • 在与字符串相互转换时,文化只会影响输出格式。不影响时区转换,这里不需要。

  • TimeZoneInfo 在 Windows 上使用的时区标识符来自 Windows 操作系统本身,有时它们的名称与您所期望的不匹配。

    • 您使用的是 Windows 时区 ID "Central European Standard Time",其显示名称为 "(UTC+01:00) Sarajevo, Skopje, Warsaw, Zagreb"
    • 对于瑞典,您实际上应该使用 ID "W. Europe Standard Time",其显示名称为 "(UTC+01:00) Amsterdam, Berlin, Bern, Rome, Stockholm, Vienna"
    • 您可以在the timezone tag wiki 中标题为“Microsoft Windows 时区数据库”的部分阅读更多相关信息。
  • 由于您似乎正在寻找特定时区的当前时间,因此您根本不应该经过本地时区。只需直接从 UTC 转换为目标时区即可。

代码应该是:

var tz = TimeZoneInfo.FindSystemTimeZoneById("W. Europe Standard Time");
var swedishTime = TimeZoneInfo.ConvertTime(DateTime.UtcNow, tz);

或者,如果您愿意,可以使用方便的方法:

var swedishTime = TimeZoneInfo.ConvertTimeBySystemTimeZoneId(DateTime.UtcNow,
                                                                 "W. Europe Standard Time")

【讨论】:

    【解决方案2】:

    只需从“var swedishTime”中删除“TimeZoneInfo.Local”即可。

    Thread.CurrentThread.CurrentCulture = new CultureInfo("sv-SE");
    TimeZoneInfo cet = TimeZoneInfo.FindSystemTimeZoneById("Central European Standard Time");
    DateTime currentDate = DateTime.SpecifyKind(DateTime.Now, DateTimeKind.Local);
    
    
    var swedishTime = TimeZoneInfo.ConvertTime(currentDate, cet);
    

    【讨论】:

      【解决方案3】:

      我遇到了同样的问题,我通过更改为 DateTimeKind.Unspecified 来解决它。

      不是这个

      var currentDateTime = DateTime.UtcNow;
      

      我把这个:

      var currentDateTime = new DateTime(DateTime.UtcNow.Ticks, DateTimeKind.Unspecified);
      

      【讨论】:

        猜你喜欢
        • 2022-01-05
        • 2022-08-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-11-26
        • 2022-08-14
        相关资源
        最近更新 更多