【问题标题】:Different DateTimeFormat for dev and test environment开发和测试环境的不同 DateTimeFormat
【发布时间】:2011-08-29 05:50:26
【问题描述】:

在我的 ASP.NET MVC 项目中 global.asax.cs 的 Application_BeginRequest() 方法中有代码:

Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(EnCultureKey);
Thread.CurrentThread.CurrentUICulture = new CultureInfo(EnCultureKey);
Thread.CurrentThread.CurrentCulture.DateTimeFormat = new CultureInfo(EnGBCultureKey).DateTimeFormat;

变量是

private const string EnCultureKey = "en-US";
private const string EnGBCultureKey = "en-GB";

在开发环境中,所有日期都是 DD/MM/YYYY 格式,但在测试环境中,它们是 MM/DD/YYYY 格式。

您能否告诉我造成这种差异的原因是什么?

更新:

请看Setting Culture for ASP.NET MVC application on VS dev server and IIS

【问题讨论】:

  • 你是如何格式化日期时间的?
  • 您是否尝试将 UICulture 设置为 en-GB。那么它的格式是否正确?如果是这样,您可以更改第三行以使用其他文化。注意:你在做奇怪的事情!首先,您分配一种文化,然后覆盖其行为。对我来说没有多大意义!

标签: c# asp.net-mvc


【解决方案1】:

如果您确实想为所有页面覆盖这些设置(而不是让用户选择),那么标准方法是 a setting in web.config :

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

如果您想使用代码,MSDN 页面还指向您覆盖 InitializeCulture()。

InitializeCulture() 发生得早,但我怀疑 Application_BeginRequest 发生得更早,并且它的影响被覆盖了。

【讨论】:

    【解决方案2】:

    尝试在 Application_Start global.asax 的方法,这将确保每次启动应用程序时,文化信息都设置为您的规范。

    确保您使用正确的时间格式,例如显示日期:

    DateTime dt = DateTime.Now; Console.WriteLine(dt.ToString("d"));

    【讨论】:

    • 1.我会尝试 Application_Start,但 Application_BeginRequest 也必须足够。 2. 我没有格式化我的 DateTime。我认为它默认使用 G - 通用格式模式。
    • 应用程序启动只发生一次。您必须根据请求执行此操作。
    【解决方案3】:

    啊,我明白了,对不起。

    我认为这当然是因为您正在改变单个线程的文化,而不是应用程序的所有线程。

    将您的代码放在应用程序中每个线程都执行的位置,例如页面加载。

    【讨论】:

    • 我正在尝试在开发和测试环境中使用相同的日期时间格式。问题是为什么相同的代码会导致不同的行为。
    【解决方案4】:

    好吧,我实际上并没有找到 IIS 设置的原因,但我已经在 Application_PreRequestHandlerExecute() 中覆盖了它,它终于奏效了:

    var culture = CultureInfo.CreateSpecificCulture(EnCultureKey);
    culture.DateTimeFormat = CultureInfo.CreateSpecificCulture(EnGBCultureKey).DateTimeFormat;
    Thread.CurrentThread.CurrentCulture = culture;
    
    culture = new CultureInfo(EnCultureKey);
    culture.DateTimeFormat = Thread.CurrentThread.CurrentCulture.DateTimeFormat;
    Thread.CurrentThread.CurrentUICulture = culture;
    

    【讨论】:

      猜你喜欢
      • 2018-07-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-02-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多