使用Razor将日期时间输出为unix时间戳

时间:2014-03-19 15:59:21

标签: c# asp.net-mvc datetime razor timestamp

我正在使用Razor输出日期时间变量,如下所示:

<td>@Html.Raw(Model.Records[i].Incident.DateRecieved)</td>

但是,我想将其更改为时间戳以便于排序,但无法找出最佳方法。我尝试使用以下代码:

<td>@Model.Records[i].Incident.DateRecieved.ToString("yyyy MM dd")</td>

但Visual Studio表示ToString没有超载需要1次争论。

有关最佳方法的任何想法吗?

由于

1 个答案:

答案 0 :(得分:2)

您的DataRecieved似乎是Nullable<DateTime>。试试这个,先获取实际值,然后使用ToString并传递日期时间格式:

<td>@Model.Records[i].Incident.DateRecieved.Value.ToString("yyyy MM dd")</td>

如果您的DateRecievednull,那么它可能会抛出异常。为了避免这种情况,您可以使用if语句:

    <td> @if(Model.Records[i].Incident.DateRecieved != null)
         { <text>@Model.Records[i].Incident.DateRecieved.Value.ToString("yyyy MM dd") </text> }
         else { <text>"default value"</text> }
    </td>
相关问题