Gbenga
Gbenga

Reputation: 183

remove time from DateTime in ASP.NET MVC

I have these questions

  1. How do I remove time from datetime (01/01/2017 instead of 01/01/2017 00:00:00)
  2. How do I display on year (2017 instead of 01/01/2017 00:00:00)

See the view below

                <td>
                @Html.DisplayFor(modelItem => item.PAYMENT_YEAR)
            </td>

PAYMENT_YEAR is DateTime in the database. I want to do it from view

Upvotes: 0

Views: 1877

Answers (1)

Shyju
Shyju

Reputation: 218952

You can call the ToShortDateString() method on the DateTime object. This will give you the short date string representation from that DateTime value.

<td>item.PAYMENT_YEAR.ToShortDateString()</td>

If you want just the year, you may access the Year property.

<td>item.PAYMENT_YEAR.Year</td>

You can use the Year property with the Html.DisplayFor helper method

<p>@Html.DisplayFor(modelItem=>item.PAYMENT_YEAR.Year)</p>

But you cannot make a method call inside DisplayFor. So you may just go with

<td>item.PAYMENT_YEAR.ToShortDateString()</td>

If the type of PAYMENT_YEAR property nullable DateTime (DateTime), you need to do a null check before calling the helper method

if (item.PAYMENT_YEAR.HasValue)
{
    <span>@Html.DisplayFor(modelItem => item.PAYMENT_YEAR.Value.Year)</span>
}

Or you can simply print the value without using the helper method along with null conditional operator

<td>item.PAYMENT_YEAR?.Year</td>

Upvotes: 1

Related Questions