After some digging and I ended up setting Thread
's CurrentCulture value to have CultureInfo("en-US") in the controller’s action method:
Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");
Here are some other options if you want have this setting on every view.
About CurrentCulture
property value:
The CultureInfo object that is returned by this property, together
with its associated objects, determine the default format for dates,
times, numbers, currency values, the sorting order of text, casing
conventions, and string comparisons.
Source: MSDN CurrentCulture
Note: The previous CurrentCulture
property setting is probably optional if the controller is already running with CultureInfo("en-US")
or similar where the date format is "MM/dd/yyyy"
.
After setting the CurrentCulture
property, add code block to convert the date to "M/d/yyyy"
format in the view:
@{ //code block
var shortDateLocalFormat = "";
if (Model.AuditDate.HasValue) {
shortDateLocalFormat = ((DateTime)Model.AuditDate).ToString("M/d/yyyy");
//alternative way below
//shortDateLocalFormat = ((DateTime)Model.AuditDate).ToString("d");
}
}
@shortDateLocalFormat
Above the @shortDateLocalFormat
variable is formatted with ToString("M/d/yyyy")
works. If ToString("MM/dd/yyyy")
is used, like I did first then you end up having leading zero issue. Also like recommended by Tommy ToString("d")
works as well. Actually "d"
stands for “Short date pattern” and can be used with different culture/language formats too.
I guess the code block from above can also be substituted with some cool helper method or similar.
For example
@helper DateFormatter(object date)
{
var shortDateLocalFormat = "";
if (date != null) {
shortDateLocalFormat = ((DateTime)date).ToString("M/d/yyyy");
}
@shortDateLocalFormat
}
can be used with this helper call
@DateFormatter(Model.AuditDate)
Update, I found out that there’s alternative way of doing the same thing when DateTime.ToString(String, IFormatProvider) method is used. When this method is used then there’s no need to use Thread
’s CurrentCulture
property. The CultureInfo("en-US")
is passed as second argument --> IFormatProvider to DateTime.ToString(String, IFormatProvider)
method.
Modified helper method:
@helper DateFormatter(object date)
{
var shortDateLocalFormat = "";
if (date != null) {
shortDateLocalFormat = ((DateTime)date).ToString("d", new System.Globalization.CultureInfo("en-US"));
}
@shortDateLocalFormat
}
.NET Fiddle