How do i set the DateTime format centrally so that at any time if I use a dateTime.ToString() in my code I get string in the ISO format(eg:2008-2-19 01:00:00)
You can add the time format as parameter to the tostring, i always use this for reference
Dim d = DateTime.Parse("2008-2-19 01:00:00")
Assert.AreEqual("2008-2-19 01:00:00", d.ToString("yyyy-M-dd HH:mm:ss"))
http://www.geekzilla.co.uk/View00FF7904-B510-468C-A2C8-F859AA20581F.htm
Regards
Iain
You should use CultureInfo to control the format when using DateTime.ToString()
EDIT:
Once you have set the CurrentCulture on your Current Thread then try the following:
DateTimeFormatInfo format = Thread.CurrentThread.CurrentCulture.DateTimeFormat;
string dateTime = DateTime.Now.ToString(format.FullDateTimePattern);
You can use extension methods to extend datetime and create a ToISOString().
check out http://msdn.microsoft.com/en-us/library/bb383977.aspx on ways to accomplish it. In the extension method you can use parameters to format the string the way you need, then you can use DateTime.ToISOString(); You could also use cultureinfo as Barry said, but I don't know if it will fit your needs.
You should update the System.Threading.Thread.CurrentThread.CurrentCulture
property.
This affects all DateTime.ToString()
in the current thread.
With the help of Albin and Barry's answers iv got the following piece to code to set the Time format centrally in the Global.asax.
using System.Globalization;
using System.Threading;
protected void Application_BeginRequest()
{
CultureInfo standardizedCulture = (CultureInfo)CultureInfo.CurrentCulture.Clone();
standardizedCulture.DateTimeFormat.DateSeparator = "-";
standardizedCulture.DateTimeFormat.LongDatePattern = "yyyy-MM-dd hh:mm:ss";
standardizedCulture.DateTimeFormat.FullDateTimePattern = "yyyy-MM-dd hh:mm:ss";
standardizedCulture.DateTimeFormat.ShortDatePattern = "yyyy-MM-dd";
Thread.CurrentThread.CurrentCulture = standardizedCulture;
Thread.CurrentThread.CurrentUICulture = standardizedCulture;
}
I think the requested format i.e. DateTIme.Now.ToString()
will have a very bad influence on your code readability (and maintainability..). Trying to override a well known behavior with a custom one is bad practice.
What I do consider a good way to use it is like so: DateTIme.Now.ToString(IsDefaultFormat)
.
Now all you need to do is add an extension method to DateTime
Which receives a bool
, and if that bool is set to true, returns the DateTime
using your "default format"