2016-01-23 61 views
1

我想知道是否有任何方法来设置全球DateTime.ToString()格式?有没有办法在全局上设置DateTime.ToString()格式?

可以说我希望我的应用程序上的所有DateTime对象都格式化为“yyyy-MM-dd”。我可以通过从对象的每个实例中调用.ToString(“yyyy-MM-dd”)来完成它。但我认为这似乎并不干净和优雅。

我可能刚刚创建了一个继承DateTime类并重写.ToString方法的新类,但是我意识到DateTime是一个无法继承和修改的密封类。有没有解决这个问题的方法?

任何帮助,将不胜感激谢谢!

+0

什么样的应用程序需要这种改变?桌面应用或Web应用程序? (WPF,WinForms,ASP.NET) – Steve

回答

5

创建扩展方法。

public static string ToSortableString(this DateTime datetime) 
{ 
    return datetime.ToString("yyyy-MM-dd"); 
} 
+0

确保你在一个非嵌套的静态函数内声明这个函数 –

2
protected void Application_BeginRequest(Object sender, EventArgs e) 
    {  
     CultureInfo newCulture = (CultureInfo)System.Threading.Thread.CurrentThread.CurrentCulture.Clone(); 
     newCulture.DateTimeFormat.ShortDatePattern = "yyyy-MM-dd"; 
     newCulture.DateTimeFormat.DateSeparator = "-"; 
     Thread.CurrentThread.CurrentCulture = newCulture; 
    } 

变化在Global.asax文件当前线程的文化,它应该让全球

或者

设置全球化在web.config中为:

<system.web> 
<globalization culture="en-NZ" uiCulture="en-NZ"/> 
</system.web> 

List Of All Country Codes

+0

不错,但它也会影响解析和格式化。如果这是OP想要的,这是没问题的。 – taffer

+0

其实我建议你的通用扩展方法的OP,但是,他/她需要它全球所以建议这种方法@taffer –

+0

Sry我忘了提及,我创建控制台应用程序而不是Web应用程序。这适用于控制台应用程序吗? – Sangadji

1

哦是的,我收到你的问题,这是解决这个问题的最好方法。 创建一个类如

public class DateFormatter 
{ 
    public DateFormatter() 
     { 
     } 
public string FormatDate(DateTime date) 
{ 
     return date.ToString("yyyy-mm-dd"); 
} 
} 

然后在App.xaml.cs创建这个类的一个静态实例这样

public static DateFormatter formatter = new DateFormatter(); 

在你的代码将只在这个格式来调用这个类

textBox1.DataContext = App.formatter.FormatDate({your-datetime-variable}); 
+1

这不是我真正需要的,我想继续使用DateTime.ToString()方法而不是创建一个新的方法或新班。但感谢您的反馈! – Sangadji

相关问题