1

I am developing a ASP.NET C# Webforms website with MySQL as the database supplying dates in its standard date format.

How can I add a custom date format to the Global.asax.cs file like the follow (non-working code):

    using System.Globalization;
    using System.Threading;

    protected void Application_BeginRequest(Object sender, EventArgs e)
    {    
      CultureInfo newCulture = (CultureInfo) System.Threading.Thread.CurrentThread.CurrentCulture.Clone();

      //Will make all dates of the format similar to 3/14/13 12:9 AM/PM 
      newCulture.DateTimeFormat = "M/d/yy h:m tt";

      Thread.CurrentThread.CurrentCulture = newCulture;
    }

Thank you for any input.

4

1 回答 1

0

DateTimeFormat属性实际上是一个DateTimeFormatInfo具有许多不同属性的类型对象。尝试这个:

CultureInfo newCulture = (CultureInfo)Thread.CurrentThread.CurrentCulture.Clone();
newCulture.DateTimeFormat.ShortDatePattern = "M/d/yy";
newCulture.DateTimeFormat.ShortTimePattern = "h:m tt";
newCulture.DateTimeFormat.LongDatePattern = "M/d/yy";
newCulture.DateTimeFormat.LongTimePattern = "h:m tt";
Thread.CurrentThread.CurrentCulture = newCulture;

现在,如果你只是在你的 ASP.Net 代码中做这样的事情:

<%= DateTime.Now %>

它应该从您的文化中汲取灵感。当然,它很容易被覆盖:

<%= DateTime.Now.ToString("ss:mm:HH dd/MM/yyyy") %>   // backwards!

你不能做任何事情来阻止它。您所能做的就是更改默认值。

短模式和长模式可能是您唯一需要更改的模式。默认(通用)模式是从这些构造的。

于 2013-07-24T01:37:47.580 回答