3

我有一个属性如下:

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

当我使用

@Html.DisplayFor(modelItem => item.EndDate)

我得到如下结果:

17.07.2013 

为什么会这样?

4

1 回答 1

2

There's several ways to do this.

Either:

  • Change the regional settings for the user running your web application
  • Use the correct CultureInfo object when formatting
  • Set the default CultureInfo object on the current thread
  • Escape the slashes

To provide a CultureInfo object when formatting:

@Html.DisplayFor(modelItem => item.EndDate.ToString("dd/MM/yyyy", CultureInfo.GetCulture("en-US")))

To set the default CultureInfo object:

Thread.CurrentThread.CurrentCulture = CultureInfo.GetCulture("en-US");

To escape the slashes, use single quotes:

[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd'/'MM'/'yyyy}")]

Note that all the code ends up in DateTime.ToString(string) or one of its overloads, so that's the place to look for clues to this.

于 2013-07-17T13:10:30.947 回答