17

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.

João Angelo
  • 56,552
  • 12
  • 145
  • 147
Dryadwoods
  • 2,875
  • 5
  • 42
  • 72
  • What do you mean by "I may be using a different culture and I still want to show the date in a different way"? – Ryand.Johnson Dec 29 '11 at 21:05
  • Imagine that the current user uses culture "pt-PT", then the DisplayFormat keep changing it to "dd-MM-yyyy" (how it should be) when I want to show it like: "dd/MM/yyyy" – Dryadwoods Dec 29 '11 at 21:14
  • It is a bit mysterious that, if the users culture says that dashes should be the separators, you're insisting on using slashes. – Damien_The_Unbeliever Dec 30 '11 at 14:50

3 Answers3

31

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

João Angelo
  • 56,552
  • 12
  • 145
  • 147
  • 1
    thank you , this works in local machine, but our website hosted in another country, it needs `MM/dd/yyyy` format else it shows validation error `The field BeginDate must be a date.`, how can i make sever to accept `dd/MM/yyyy` format? – Shaiju T Apr 02 '15 at 05:58
2

Change the Short date format of the server' Regional settings to use slashes e.g. yyyy/MM/dd.
This solved the issue for me.

  • thanks for the comment but that's not a correct solution since the server/farm/cloud can be "providing" several different projects OR the web application in question may offer multi-culture functionalities. – Dryadwoods Nov 29 '12 at 08:48
0

Can you change it to DataFormatString = "{0:d}"

That should give you the short date pattern of mm/dd/year

Ryand.Johnson
  • 1,906
  • 2
  • 16
  • 22