Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 345
Dryadwoods Avatar asked Dec 29 '11 20:12

Dryadwoods


1 Answers

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}"

like image 199
João Angelo Avatar answered Nov 02 '22 19:11

João Angelo