我的剃刀代码中有一个表,它循环遍历模型中的所有项目,并为每个项目创建一个表格行。我想弄清楚如何将日期格式化为MM / dd / yyyy而不是默认的“MM / dd / yyyy HH:mm:ss”格式。
<table class="table-condensed">
<thead>
<tr>
<th>Company</th>
<th>Contract No</th>
<th>Description</th>
<th>Expires</th>
</tr>
</thead>
<tbody>
@foreach (var item in Model)
{
<tr>
<td>@Html.ActionLink(@item.CompanyName, "ViewContract", new { contractID = @item.ID }) </td>
<td width="200">@item.ContractNumber</td>
<td>@item.Description</td>
<td>@item.ExpireDate</td>
</tr>
}
</tbody>
</table>
我已经尝试过@ item.ExpireDate.ToString(“MM / dd / yyyy”),但它会抛出一个错误,说明.ToString没有参数。
答案 0 :(得分:5)
如果您正在使用c#6功能,则可以使用空条件。
@(item.ExpireDate?.ToString("MM/dd/yyyy"))
答案 1 :(得分:1)
我正在使用PagedList NuGet包,这使得Html帮助器调用有点不同。我可以通过在数据模型构造函数中指定日期格式然后使用显示帮助程序来格式化日期。
在数据模型中:
[DisplayFormat(DataFormatString = "{0: MM/dd/yyyy}")]
public Nullable<System.DateTime> ExpireDate { get; set; }
在剃刀中:
<table class="table-condensed">
<thead>
<tr>
<th>Company</th>
<th>Contract No</th>
<th>Description</th>
<th>Expires</th>
</tr>
</thead>
<tbody>
@foreach (var item in Model)
{
<tr>
<td>@Html.ActionLink(@item.CompanyName, "ViewContract", new { contractID = @item.ID }) </td>
<td width="200">@item.ContractNumber</td>
<td>@item.Description</td>
<td>@Html.DisplayFor(modelItem => item.ExpireDate)<td>
</tr>
}
</tbody> </table>
答案 2 :(得分:0)
您现在也可以使用
@item.ExpireDate?.ToShortDateString()
,它将DateTime值转换为“ M / d / yyyy”日期格式