Formatting Date in ASP.NET MVC

I am having a little trouble figuring out how to format a date in my view. In my application, I have an Edit button. Once clicked on, the text box becomes editable with the date value. However, it is also showing me the time, which I don't want to see. How can I fix that?


The Problem with the Application

The code in my Model Class:

 [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
 public DateTime? Planned_Date { get; set; }

The code in my View class:

<td class="Planned_Date">
    @Html.TextBoxFor(x => item.Planned_Date)

The onClick():

  $("body").on("click", "#tblCustomers .Edit", function () {
            var row = $(this).closest("tr");
            $("td", row).each(function () {
                if ($(this).find("input").length > 0) {

1 answer

  • answered 2018-10-11 19:08 Jack

    You need to edit your DataAnnotation on your model.

    [DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}")]

    Add in the ApplyInEditMode property:

    [DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}"), ApplyFormatInEditMode = true)]

    This will make the DataFormartString be applied to textboxes generated with EditorFor, or other editors. From this MSDN article,

    The ApplyFormatInEditMode setting specifies that the specified formatting should also be applied when the value is displayed in a text box for editing. (You might not want that for some fields — for example, for currency values, you might not want the currency symbol in the text box for editing.)

    Then, instead of declaring the input element in your view and setting the value from the model, you should update your view to use the Razor helper, Html.EditorFor. Refer to the Microsoft API for more information.

    <td class="Planned_Date">

    You may have to adjust the example code to fit your situation (for example, adding classes or styles). Your JavaScript should still work.

    Note: The DisplayFormat DataAnnotation does not apply to inputs generated with Html.TextboxFor. It only applies to textboxes (or other editors) generated with Html.EditorFor and Razor Display helpers.