How to format dates in MVC 5 Razor

13,246

Solution 1

I am using the PagedList NuGet package which makes the Html helper calls a little different. I was able to format the date by specifying the date format in the data model constructor and then using the display helper.

In the data model:

[DisplayFormat(DataFormatString = "{0: MM/dd/yyyy}")] 
public Nullable<System.DateTime> ExpireDate { get; set; }

In the razor:

<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>

Solution 2

If you're using c# 6 features you can use a null-conditional.

@(item.ExpireDate?.ToString("MM/dd/yyyy"))

Share:
13,246

Related videos on Youtube

Snicklefritz
Author by

Snicklefritz

Updated on September 15, 2022

Comments

  • Snicklefritz
    Snicklefritz over 1 year

    I have a table in my razor code that loops through all of the items in the model and creates a table row for each item. I'm trying to figure out how to format the date to MM/dd/yyyy instead of the default "MM/dd/yyyy HH:mm:ss" format.

    <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>
    

    I have tried @item.ExpireDate.ToString("MM/dd/yyyy") but it throws an error saying that .ToString does not take an argument.

  • cdonner
    cdonner almost 3 years
    - error: Operator '?' cannot be applied to operand of type 'DateTime' ?
  • c-sharp-and-swiftui-devni
    c-sharp-and-swiftui-devni almost 3 years
    C# 6 feature ? @cdonner