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

不羁的心 提交于 2019-12-18 12:57:40

问题


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.


回答1:


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




回答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.




回答3:


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

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



来源:https://stackoverflow.com/questions/8673174/why-does-displayformat-with-dataformatstring-changes-slash-to-dash

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!