Search code examples
c#asp.net-mvcdatetimeformat

How to display only DATE part on View in ASP.NET MVC


I'm trying to display only date part on my view, value I'm getting from database is pretty big and I really don't need informations like hrs, mns, seconds etc, I'm only interested in date, for example I would like to display only :

17/04/2017 

And this is what I've tried so far:

<td>
       @Html.DisplayFor(modelItem => ((DateTime)item.ValidFrom).ToString("dd/MM/yyyy"))
</td>
<td>
       @Html.DisplayFor(modelItem => ((DateTime)item.ValidTo).ToString("dd/MM/yyyy"))
</td>

Here is the DateType of my Properties:

public System.DateTime ValidFrom { get; set; }
public Nullable<System.DateTime> ValidTo { get; set;

And here is the issue I get: [![enter image description here][1]][1]


Solution

  • Just Output Directly

    Instead of using the DisplayFor() helper method, you might consider just outputting the values directly if that would work for you:

    <td>
       @modelItem.ValidFrom.ToString("dd/MM/yyyy")
    </td>
    <td>
       @modelItem.ValidTo?.ToString("dd/MM/yyyy")
    </td>
    

    Consider ViewModel-Level Formatting

    Another possibly better option, would be performing this within your ViewModel itself as opposed to within the View:

    public System.DateTime ValidFrom { get; set; }
    public Nullable<System.DateTime> ValidTo { get; set; }
    
    // These will be formatted versions of the properties specifically for output
    public string FormattedFrom => ValidFrom.ToString("dd/MM/yyyy");
    public string FormattedTo => ValidTo?.ToString("dd/MM/yyyy") ?? "Present";
    

    And then simply use those properties instead:

    <td>
       @Model.FormattedFrom
    </td>
    
    <td>
       @Model.FormattedTo
    </td>