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!
The ToString (String) method returns the string representation of the date and time in the calendar used by the current culture. If the value of the current DateTime instance is earlier than MinSupportedDateTime or later than MaxSupportedDateTime, the method throws an ArgumentOutOfRangeException.
To format it using a specific date and time format specifier, call the ToString(String) method. To format it using the general date and time format specifier ('G') for a specific culture, call the ToString(IFormatProvider) method.
The value of the current DateTime object is formatted using the general date and time format specifier ('G'). To format it using a specific date and time format specifier, call the ToString (String) method. To format it using the general date and time format specifier ('G') for a specific culture, call the ToString (IFormatProvider) method.
Getting a string that contains the date and time in a specific format. For example, the "MM/dd/yyyyHH:mm" format string displays the date and time string in a fixed format such as "19//03//2013 18:06". The format string uses "/" as a fixed date separator regardless of culture-specific settings.
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
Create an extension method.
public static string ToSortableString(this DateTime datetime)
{
return datetime.ToString("yyyy-MM-dd");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With