简体   繁体   English

有没有办法全局设置DateTime.ToString()格式?

[英]Is there a way to set DateTime.ToString() format globally?

I would like to know is there any way to set DateTime.ToString() format globally? 我想知道有没有办法全局设置DateTime.ToString()格式?

Lets say that I want all of my DateTime objects on my application to be formatted to "yyyy-MM-dd." 让我们说我希望我的应用程序上的所有DateTime对象都被格式化为“yyyy-MM-dd”。 I could've done it by calling .ToString("yyyy-MM-dd") from each instances of the object. 我可以通过从对象的每个实例调用.ToString(“yyyy-MM-dd”)来完成它。 But I think that would not seem to be clean and elegant. 但我认为这似乎并不干净优雅。

I could've just created a new class that inherits DateTime class and override the .ToString method, but I realized that DateTime is a sealed class which I cannot inherit and modify. 我可以创建一个继承DateTime类并覆盖.ToString方法的新类,但我意识到DateTime是一个密封的类,我不能继承和修改它。 Is there any workaround for this issue? 这个问题有解决方法吗?

Any help would be appreciated thanks! 任何帮助将不胜感激!

Create an extension method. 创建扩展方法。

public static string ToSortableString(this DateTime datetime)
{
    return datetime.ToString("yyyy-MM-dd");
}
    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;
    }

change the current thread culture in your Global.asax file and it Should make it globally 更改Global.asax文件中的当前线程文化,它应该全局

Or 要么

Set the Globalization in web.config as: 将web.config中的Globalization设置为:

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

List Of All Country Codes 所有国家代码清单

Oh yeah.,i get your question and this is the best way to approach such a problem. 哦,是的,我得到你的问题,这是解决这个问题的最佳方法。 Create a class eg 创建一个类,例如

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

Then create a static instance of this class in App.xaml.cs like this 然后在App.xaml.cs中创建此类的静态实例,如下所示

public static DateFormatter formatter = new DateFormatter();

In your code you will just be calling this class in this format 在您的代码中,您将以此格式调用此类

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM