Global.asax.cs跨网站的自定义日期格式

时间:2013-07-24 00:10:37

标签: c# webforms date-format

我正在开发一个ASP.NET C#Webforms网站,其中MySQL作为数据库提供标准日期格式的日期。

如何将自定义日期格式添加到Global.asax.cs文件中,如以下(非工作代码):

    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;
    }

感谢您的任何意见。

1 个答案:

答案 0 :(得分: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!

你无法阻止这一点。您所能做的就是更改默认值。

短期和长期模式可能是您需要更改的唯一模式。默认(一般)模式由这些构成。