Sangadji
Sangadji

Reputation: 321

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?

Lets say that I want all of my DateTime objects on my application to be formatted to "yyyy-MM-dd." I could've done it by calling .ToString("yyyy-MM-dd") from each instances of the object. 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. Is there any workaround for this issue?

Any help would be appreciated thanks!

Upvotes: 8

Views: 11091

Answers (3)

Arijit Mukherjee
Arijit Mukherjee

Reputation: 3875

    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

Or

Set the Globalization in web.config as:

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

List Of All Country Codes

Upvotes: 15

Timothy Macharia
Timothy Macharia

Reputation: 2926

Oh yeah.,i get your question and this is the best way to approach such a problem. Create a class e.g

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

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

Upvotes: 1

Gy&#246;rgy Kőszeg
Gy&#246;rgy Kőszeg

Reputation: 18013

Create an extension method.

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

Upvotes: 7

Related Questions