2013-07-24 24 views
1

我开发一个ASP.NET C#Web表单网站与MySQL作为数据库提供其标准的日期格式的日期。的Global.asax.cs自定义日期格式在整个网站

我如何添加一个自定义日期格式的文件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; 
    } 

谢谢你的任何输入。

回答

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! 

你不能做任何事情来防止这种情况。你所能做的只是改变默认值。

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

+0

为什么你需要调用'CurrentCulture.Clone()',而不是简单地使用'CurrentCulture.DateTimeFormat.ShortDatePattern = “”'等? – Sinjai