Converting DateTime format using razor

2019-01-03 01:49发布

What is wrong with the following?

@Convert.ToDateTime((@item.Date.ToShortDateString())," dd - M - yy")

@item.Date is showing 20/11/2005 12:00 a.m and I want to display 20 Nov 2011

9条回答
Luminary・发光体
2楼-- · 2019-01-03 02:31

For Razor put the file DateTime.cshtml in the Views/Shared/EditorTemplates folder. DateTime.cshtml contains two lines and produces a TextBox with a date formatted 9/11/2001.

@model DateTime?
@Html.TextBox("", (Model.HasValue ? Model.Value.ToShortDateString() : string.Empty), new { @class = "datePicker" })
查看更多
We Are One
3楼-- · 2019-01-03 02:31

In general, the written month is escaped as MMM, the 4-digit year as yyyy, so your format string should look like "dd MMM yyyy"

DateTime.ToString("dd MMM yyyy")
查看更多
太酷不给撩
4楼-- · 2019-01-03 02:37

Try:

@item.Date.ToString("dd MMM yyyy")

or you could use the [DisplayFormat] attribute on your view model:

[DisplayFormat(DataFormatString = "{0:dd MMM yyyy}")]
public DateTime Date { get; set }

and in your view simply:

@Html.DisplayFor(x => x.Date)
查看更多
登录 后发表回答