Why does DisplayFormat with DataFormatString changes "/" (slash) to "-" (dash)?

Dryadwoods picture Dryadwoods · Dec 29, 2011 · Viewed 12.1k times · Source

I'm using the following code

// Model
[DisplayFormat(
    ApplyFormatInEditMode = true, 
    DataFormatString = "{0:dd/MM/yyyy}")]
public DateTime StartDate { get; set; }

// View
@Html.EditorFor(model => model.StartDate)

to format the StartDate but the result is xx-xx-xxxx instead of xx/xx/xxxx. How can I solve this and always use the xx/xx/xxxx format?

UPDATE: Changing the culture to en-US seems to work:

var culture = new CultureInfo(userCulture);
System.Threading.Thread.CurrentThread.CurrentCulture = "en-US";
System.Threading.Thread.CurrentThread.CurrentUICulture = "en-US";

but this is not a solution because I may be using a different culture and I still want to show the date in a different way.

If the current culture tells that the date should display dd-MM-yyyy then using DisplayFormat as above has no effect and the dates do not display like dd/MM/yyyy.

Answer

João Angelo picture João Angelo · Dec 30, 2011

Use DataFormatString = @"{0:dd\/MM\/yyyy}" instead. Since the / identifies a character that should be replaced by the default date separator for the current culture, you need to escape it in order for it to be used as a literal in the format.

This way you have a fixed format instead of one that dynamically uses the date separator of the current culture.

An alternative to escape the / character can be: DataFormatString = "{0:dd'/'MM'/'yyyy}"