为什么DisplayFormat与DataFormatString变更]; /" (斜线),以" - " (短跑)?斜线、短跑、DisplayFormat、DataFo

2023-09-03 06:02:25 作者:小火柴

我用下面的code

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

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

格式化开始日期但结果是 XX-XX-XXXX 而不是 XX / XX / XXXX 。我怎样才能解决这个问题,并始终使用 XX / XX / XXXX 格式?

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?

更新: 改变文化的en-US 似乎工作:

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.

如果当前的文化告诉该日期应显示 DD-MM-YYYY 然后用 DisplayFormat 如以上没有影响,日期不显示如 DD / MM / YYYY

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.

推荐答案

使用 DataFormatString = @{0:DD \ / MM \ / YYYY}代替。因为 / 识别的字符应当由默认日期分隔为当前培养被替换,则需要逃避它以便它被用作在一个文字格式。

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.

这是另一种逃避 / 字符可以是: DataFormatString ={0:DD'/'MM'/'YYYY}

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