62

I'm using MVC4 and Entity Framework to develop an intranet web app. I have a list of persons which I can edit. When I access the edit view, in the textbox "Start date", the date is displayed like this : 7/11/2013 00:00:00 . What I want to do is to display it in the format yyyy/MM/dd. I tried the String.Format("{0:yyyy/MM/dd}", item.StartDate) but it does not work. I also tried with the annotation [DisplayFormat(DataFormatString = "{0:dd MMM yyyy}")] but it does not work neither.

In my view I have this :

<div class="editor-field">
        @Html.TextBoxFor(model => model.StartDate, new { @class = "datepicker" })
        @Html.ValidationMessageFor(model => model.StartDate)
    </div>

Any idea about how to do?

Owen
  • 728
  • 7
  • 17
Traffy
  • 2,803
  • 15
  • 52
  • 78
  • 1
    It would have worked if you'd actually used EditorFor as your title suggested... you used TextBoxFor though... which doesn't understand formatting dataattributes. – Erik Funkenbusch Oct 27 '14 at 07:29
  • For the users of Mvc 4 and above here is the Answer http://stackoverflow.com/questions/1961114/date-only-from-textboxfor – Khalil Liraqui May 10 '17 at 20:22
  • 1
    If you are not using EditorFor(), why do you put that in the title? I need solution for EditorFor(), **not** the TextBoxFor() you are looking for. For consideration of others, please edit the title and use `TextBoxFor()` instead? Thanks. – Just a HK developer Jun 15 '18 at 07:09
  • Related, and answer: https://stackoverflow.com/questions/33247295/show-only-the-date-in-html-editorfor-helper/52861439#52861439 – vapcguy Oct 17 '18 at 20:30
  • Duplicate of: https://stackoverflow.com/questions/1961114/date-only-from-textboxfor – vapcguy Oct 17 '18 at 20:31

7 Answers7

112
@Html.TextBoxFor(m => m.StartDate, 
    new { @Value = Model.StartDate.ToString("yyyy/MM/dd"), @class="datepicker" })
Maxime
  • 8,645
  • 5
  • 50
  • 53
Vladimir
  • 7,345
  • 4
  • 34
  • 39
78

enter image description here

Your question asks for EditorFor() but the code you provided uses TextboxFor().

In your Model (e.g. MyModel.cs), you should have:

public class MyModel
{
    [DisplayFormat(DataFormatString = "{0:yyyy/MM/dd}", ApplyFormatInEditMode = true)]
    public DateTime StartDate { get; set; }
}

In your View (e.g. Index.cshtml), you simply use it like you wrote it:

@Html.EditorFor(m => m.StartDate, new { htmlAttributes = new { @class = "datepicker" } })

It works as expected.

By doing it that way (instead of altering the way it's displayed in your View), you could reuse your model somewhere else and don't have to specify how to display the date in your View. So, if for some reason, you have to change the display format, you would only need to change it once.

The solution also works for MVC 5.

Maxime
  • 8,645
  • 5
  • 50
  • 53
  • 3
    This is a great answer. Better than the accepted answer. Although note that in order for this to work in Chrome the date format string needs to be `yyyy-MM-dd` – bowerm Sep 09 '15 at 09:53
  • 3
    Ahh, the trick was to add htmlAttributes around the custom attributes. Good to know. Thank you. – sharad shrestha Aug 03 '16 at 15:54
  • The better answer, view model should be the place! –  Sep 26 '16 at 20:01
  • thnx , but this answer remove the Datepicker :( it's only text box formate – Tuta Jun 07 '17 at 11:08
  • @Tuta This answer does not remove anything. It might be incomplete in your specific case and maybe you need to adjust it to suit your context. – Maxime Jun 07 '17 at 15:31
  • I have my format set to "dd/mm/yyyy" and it works on display, but as soon as I open the datepicker and start selecting dates it changes to "mm/dd/yyyy".. hmmm – Murphybro2 Aug 08 '17 at 08:19
  • @Murphybro2 Check how your date picker is configured. This should have nothing to do with the back-end code. – Maxime Jan 31 '18 at 16:57
  • Found a similar answer that did not include "ApplyFormatInEditMode = true". Adding this made all the difference for me. – codemonkeytony Feb 28 '19 at 01:21
4

The top easy for me , was adding the type attribute,

@Html.EditorFor(model => model.FechaRegistro, new { htmlAttributes = new { @class = "form-control oso" ,@type = "date"  } })
3

Html.EditorFor also work


@Html.EditorFor(model => model.StartDate, new { htmlAttributes = new { @class = "datepicker", @Value = model.StartDate.ToString("yyyy/MM/dd") } })
s.c
  • 768
  • 6
  • 15
  • 1
    Note that I had to make the "Value" portion: `@Value = model.StartDate.Date.ToString("yyyy-MM-dd")` in order for my value to show up (and use `.Data.Value.ToString("yyyy-MM-dd")` when I had nullable dates) . – vapcguy Oct 17 '18 at 21:00
0

I'm a noob here (and also with MVC) and this is just an variation of Maxime's using a partial class...

If you've got a DB-first model and don't want to alter it directly for fear of losing your changes, just do this same thing in your own partial class. Just add a new class/file within your Models folder and make sure it uses the same namespace as your generated models.

So here's how you would declare the metadata to both format the date & modify the display name of another value (ie: to abbreviate the column headers in a table)

namespace MyProjectName.Models
{

    public class MyModelMeta
    {

        [DisplayFormat(DataFormatString = "{0:yyyy/MM/dd}", ApplyFormatInEditMode = true)]  // format used by Html.EditorFor
        public DateTime StartDate;

        [Display(Name = "User ID")] // abbreviation shown in Html.DisplayNameFor
        public string SomeReallyLongUserIDColumn;

    }

    [MetadataType(typeof(MyModelMeta))]
    public partial class MyModel
    {

    }
}
xyvyx
  • 11
  • 3
  • Your answer is not answering the original question. More than that, you are using your own question and provide an answer that is really off-topic. I did not downvoted your answer but you should adjust it or delete it. – Maxime Dec 08 '15 at 19:01
  • Actually, Maxime, it provides an example that applies a date format to an EditorFor very similar to how yours did. Your code,however, would be clobbered if you were using a Database First model and chose to update that model. My example was using a simple short-date format of "d" and I was showing how it was structured in this class along with one other column. I suppose I could have renamed my date column to "StartDate", but I figured people would get the idea... – xyvyx Dec 09 '15 at 16:15
  • Now I get what you mean. That said, I still think you should adapt your answer to the context and also add a couple of lines in your `Contacts` (with an "s" ?) class to make it more clear. I had to do it that way when I used Model-First. I switched to Code-First and would not go back! :-) – Maxime Dec 09 '15 at 16:29
  • Also, when you said "this is just an extension [...]", I thought you were refering to [Extension Methods](https://msdn.microsoft.com/en-CA/library/bb383977.aspx). So, your code has nothing to do with taking my answer and creating an extension. That's where I was confused. – Maxime Dec 09 '15 at 16:31
0

try this.. convert the date value as a htmlAttribute within textboxfor.. that can solve your problem

<div class="editor-field">
    @Html.TextBoxFor(model => model.StartDate, new { htmlAttributes = new { @Value = Model.StartDate.ToString("yyyy/MM/dd"), type = "date"  }})
    @Html.ValidationMessageFor(model => model.StartDate)
</div>
nAyeem
  • 19
  • 3
  • You can not throw a block of code as an answer, without giving explanations and clues of why you code it this way. – Léa Gris Aug 28 '19 at 19:22
  • sorry, i i didn't think of that.. I've added a short explanation, hope it's ok now. – nAyeem Sep 27 '19 at 21:00
0

None of the above worked for me. Had to do the following:

<input type="date" class="form-control" value="@Model.StartDate.Value.ToString("yyyy-MM-dd")" name="StartDate" id="StartDate" />

Vinicius Sin
  • 1,571
  • 11
  • 8