Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set Default DateTime Format c#

Is there a way of setting or overriding the default DateTime format for an entire application. I am writing an app in C# .Net MVC 1.0 and use alot of generics and reflection. Would be much simpler if I could override the default DateTime.ToString() format to be "dd-MMM-yyyy". I do not want this format to change when the site is run on a different machine.

Edit - Just to clarify I mean specifically calling the ToString, not some other extension function, this is because of the reflection / generated code. Would be easier to just change the ToString output.

like image 665
Matthew Hood Avatar asked Sep 07 '09 12:09

Matthew Hood


People also ask

What is default DateTime format in C#?

vb.net date formatting vs c# datetime formatting. -3. DateTime conversion from MM/dd/yyyy TO dd/MM/yyyy. 1.

How do I change the date format in C sharp?

string formatted = date. ToString("dd-MM-yyyy");

What is the universal date format?

YYYY-MM-DD where YYYY is the year in the usual Gregorian calendar, MM is the month of the year between 01 (January) and 12 (December), and DD is the day of the month between 01 and 31.


1 Answers

The "default format" of a datetime is:

ShortDatePattern + ' ' + LongTimePattern 

at least in the current mono implementation. This is particularly painful in case you want to display something like 2001-02-03T04:05:06Z i.e. the date and time combined as specified in ISO 8606, but not a big problem in your case:

using System; using System.Globalization; using System.Threading;  namespace test {     public static class Program {         public static void Main() {             CultureInfo culture = (CultureInfo)CultureInfo.CurrentCulture.Clone();             culture.DateTimeFormat.ShortDatePattern = "dd-MMM-yyyy";             culture.DateTimeFormat.LongTimePattern = "";             Thread.CurrentThread.CurrentCulture = culture;             Console.WriteLine(DateTime.Now);         }     } } 

This will set the default behavior of ToString on datetimes to return the format you expect.

like image 151
Paolo Tedesco Avatar answered Oct 19 '22 09:10

Paolo Tedesco