asp.net-mvc 如何在 Razor 视图中格式化 DateTime?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8026079/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I format a DateTime in a Razor view?
提问by Samantha J T Star
I have variables like:
我有如下变量:
DateTime crd = a.CreationDate; (shown as a variable in C# but available in razor views)
I want to show these as a date using the format: 11/06/2011 02:11
我想使用以下格式将这些显示为日期:11/06/2011 02:11
Ideally I would like to have some kind of HTML helper for this. Anyone out there already have something that might meet my needs?
理想情况下,我想有这个某种HTML帮手。有没有人已经有了可以满足我需求的东西?
回答by JustinStolle
You could create a Display Template or Editor Template like in this answer, but the format would apply to all DateTime variables in the given scope (maybe good or bad).
您可以像在这个答案中一样创建一个显示模板或编辑器模板,但该格式将应用于给定范围内的所有 DateTime 变量(可能好也可能坏)。
Using the DisplayFormatattribute works well to define formats for individual fields.
使用DisplayFormat属性可以很好地定义各个字段的格式。
Remember to use @Html.DisplayFor(model=>model.crd)and/or @Html.EditorFor(model=>model.crd)syntax for either of the above.
请记住对上述任何一个使用@Html.DisplayFor(model=>model.crd)和/或@Html.EditorFor(model=>model.crd)语法。
You can always use the DateTime.ToString()method in your views as well for more ad hoc formatting.
您可以随时使用的DateTime.ToString()方法在你的意见,以及对更特设格式。
@crd.ToString("MM/dd/yyyy HH:mm") // time using a 24-hour clock
回答by Damith
in your model you can set [DisplayFormat]attribute with formatting as you wish
在模型中,您可以设置 [DisplayFormat]如你所愿属性与格式
[DisplayFormat(DataFormatString = "{0:dd MMM yyyy}")]
pubilc DateTime CreationDate{ get; set }
回答by Ravi Ram
How about
怎么样
@crd.ToShortDateString()
@crd.ToShortDateString()
回答by user4439128
Use this code to format your date:
使用此代码格式化您的日期:
@string.Format("{0:ddd}",Convert.ToDateTime(Html.DisplayFor(model => model.Booking.BookingFromDate).ToString()))
If your date field with required attribute then you don't want to validate nullvalue.
Other wise you can use ternary operator
如果您的日期字段具有 required 属性,那么您不想验证null值。否则,您可以使用三元运算符
回答by Cagdas Bsn
Try Razor View
尝试剃刀视图
@Html.Raw(item.Today_Date.Date.ToString("dd.MM.yyyy"))
@Html.Raw(item.Today_Date.Date.ToString("dd.MM.yyyy"))
回答by JoshYates1980
If you have a list of dates and want to grab the first:
如果您有日期列表并想获取第一个:
Begin Date: @string.Format("{0:MM/dd/yyyy}", Convert.ToDateTime(Model.aList.Where(z => z.Counter == 1).Select(z => z.Begin_date).First()))

