【问题标题】:ValueProviderResult.ConvertTo returns different dates locally and in the cloudValueProviderResult.ConvertTo 在本地和云端返回不同的日期
【发布时间】:2019-10-18 21:00:18
【问题描述】:

我有下一个自定义模型绑定器:

public class WebApiModelBinderDateTime : IModelBinder
{
    public bool BindModel(HttpActionContext executionContext, ModelBindingContext bindingContext)
    {
        ValueProviderResult value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);

        if (value == null)
        {
            return false;
        }

        DateTime date = (DateTime)value.ConvertTo(typeof(DateTime), CultureInfo.CurrentCulture);
        date = DateTime.SpecifyKind(date, DateTimeKind.Utc);
        bindingContext.Model = date;

        return true;
    }
}

文化在 web.config 中设置如下:

<globalization culture="en-GB" enableClientBasedCulture="false" uiCulture="en-GB" />

在 global.asax 中是这样的:

CultureInfo culture = CultureInfo.CreateSpecificCulture("en-GB");
Thread.CurrentThread.CurrentCulture = culture;
Thread.CurrentThread.CurrentUICulture = culture;

问题是这个活页夹在本地和远程返回不同的日期。

例如2019-06-03T09:53:26.651Z 将在本地转换为2019-06-03 10:53:26,但在云端转换为2019-06-03 09:53:26(这是部署到 Azure 云服务的旧系统)。

我尝试在本地和远程调试,但没有发现CultureInfo.CurrentCultureModelBindingContextValueProviderValueProviderResult 之间有任何区别。

还有什么会导致不同的时区?

【问题讨论】:

    标签: .net datetime timezone globalization azure-cloud-services


    【解决方案1】:

    一些事情:

    • 文化设置和时区是完全正交的概念。文化可以影响字符串的格式或应用的日历系统,但不会影响时区。它们彼此无关。

    • 您指定了DateTimeKind.Utc,因此无论您在何处使用它,结果值都将被序列化,并带有一个尾随Z,表示UTC。如果这些值确实是基于 UTC 的,那么一切都很好,没有什么可做的了。但是,如果您将这些应用于可能代表不同时区时间的任意值,则设置 UTC 类型将无济于事。相反,您可以考虑使用DateTimeOffset 类型而不是DateTime

    • 您没有向我们展示如何应用此模型绑定器或如何使用 API。假设您的 API 正确传递了基于 UTC 的结果(使用Z),那么您对时区的担忧完全基于客户端代码的解释。

    • 直接回答“还有什么会导致不同时区?”

      • 如果您调用DateTime.NowDateTimeOffset.NowTimeZoneInfo.Local 或使用DateTimeKind.Local.ToLocalTime() 等,以及几个 本地时间转换的API,如@987654331 @,那么服务器的本地时区设置(从日期和时间控制面板或设置页面)控制该时区。它是服务器上所有应用程序的服务器范围设置。您也可以在命令行使用tzutil.exe查看或控制它。
      • 如果您遵循依赖服务器时区设置的最佳实践(仅使用基于 UTC 的 API 或使用特定时区的 API),那么你没有这个顾虑。
      • 不要忘记,世界并非都在一个时区。因此,如果您的服务器在一个时区(例如 UTC)中发出时间,而您的客户端代码显式或隐式地将其转换为另一个时区(例如其本地时间),那么值不同是完全正常的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-25
      • 2014-08-20
      • 1970-01-01
      • 1970-01-01
      • 2015-06-19
      • 1970-01-01
      相关资源
      最近更新 更多