ASP.Net MVC Razor Remove Time From DateTime Property

42,590

Solution 1

You can use @item.startDate.Value.ToShortDateString() (adding the proper validation for null value)

Solution 2

You can use a DisplayFormat attribute on your model startDate property:

[DisplayFormat(DataFormatString="{0:dd/MM/yyyy}")]
public DateTime? startDate { get; set; }

The just use DisplayFor(modelItem => item.startDate)

Another option is to create a read-only property just for the formatting:

public String startDateFormatted { get { return String.Format("{0:dd/MM/yyyy}", startDate); } }

And use DisplayFor(modelItem => item.startDateFormatted)

Solution 3

For me I was able to do something similar to the above answer, but using "Value" attribute kept giving errors.

<td>
@item.DOB.ToShortDateString()
</td>

Other things to note: I'm using ASP.Net Core MVC with the .NET 5 framework so not sure how that's classified or called these days.

Hope this helps someone else coming across this issue later in the future.

Share:
42,590
tcode
Author by

tcode

Updated on August 07, 2021

Comments

  • tcode
    tcode over 2 years

    I am developing an ASP.Net MVC 3 Web application using Razor Views. I have the following ViewModel which is passed to my Razor View and iterated through to display a list of records.

    ViewModel

    public class ViewModelLocumEmpList
    {
        public IList<FormEmployment> LocumEmploymentList {get; set;}
    }
    

    View

    <table>
      <tr>
       <th>Employer</th>
       <th>Date</th>
       </tr>
        @foreach (var item in Model.LocumEmploymentList) {
          <tr>
            <td>@item.employerName</td>
            <td>@item.startDate</td>
          </tr>
          }
          </table>
    

    My problem is that the line

    @Html.DisplayFor(modelItem => item.startDate)
    

    Returns a date like this 20/06/2012 00:00:00, and I would like it to remove the time and just display the date, ie, 20/06/2012.

    I have tried adding

    @Html.DisplayFor(modelItem => item.startDate.Value.ToShortDateString())
    

    And

    DisplayFor(modelItem => item.startDate.HasValue ? item.startDate.Value.ToShortDateString(): "")
    

    However, they both return the following error message at runtime

    Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions.
    

    I have looked at Darin Dimitrov’s answer here Converting DateTime format using razor

    However, I don’t have access to the startDate property in my ViewModel, my ViewModel returns an IList of FormEmployment objects which you can see above.

    If anyone has any idea’s on how to remove the time from the date time property then I would be greatly appreciative.

    Thanks.

    Also, my startDate property is Nullable.

    Update

    Based on PinnyM's answer, I added a partial class (see below) to place the [DisplayFormat] attribute on the startDate property.

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

    However, my Razor View still displays 20/06/2012 00:00:00 using the following code

    @Html.DisplayFor(modelItem => item.startDate)
    

    Any idea's?

    Thanks.

  • tcode
    tcode almost 12 years
    As I stated in my question, I have already tried using @Html.DisplayFor(modelItem => item.startDate.Value.ToShortDateString()) which results in the same error as stated above.
  • pollirrata
    pollirrata almost 12 years
    Don't use DisplayFor, just set <td>@item.startDate.Value.ToShortDateString()</td>
  • tcode
    tcode almost 12 years
    @Pollirata: Cheers, this works. But, can you explain why it works without DisplayFor, and why it doesn't work when I include DisplayFor? Thanks.
  • tcode
    tcode almost 12 years
    I can't do this, because my Model Classes are created by a T4 Template, therefore, every time I re-generate the template, my change will be overridden, although, I could maybe create a partial class to hold this single property.
  • tcode
    tcode almost 12 years
    Please see my Updated Question. Thank you.
  • pollirrata
    pollirrata almost 12 years
    I'm not sure, I haven't used that on loops before... But I had a similar problem and that's the way I solved it
  • PinnyM
    PinnyM almost 12 years
    The reason is because DisplayFor is expecting an Expression lambda which can only be parsed using simple constructs (properties, boolean operators, etc)
  • PinnyM
    PinnyM almost 12 years
    See stackoverflow.com/questions/2105580/… and ryanhayes.net/blog/… for a way to do this using a partial class and metadata class.
  • V-SHY
    V-SHY almost 9 years
    FYI, if the startDate is not nullable, no need the Value and direct @item.startDate.ToShortDateString()
  • pollirrata
    pollirrata almost 9 years
    @V-SHY the question poster specified "Also, my startDate property is Nullable." :)
  • Max
    Max about 5 years
    add the attribute ApplyFormatInEditMode to the dataAnnotations of the first solution: [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/mm/yyyy}")]