16

I am trying to display a datetime field retrieved froma database in my razor file with the following:

 @Html.EditorFor(model => model.RequestDate);

I know with 100% certainty the RequestDate is not null, as I examined the model that was passed in the view, and it was the date from the database. However, the datetime textbox still displays "mm/dd/yyyy". I don't know why it is not display the date. Any ideas? Thank you.

Here is my model:

      [Display(Name = "Time")]
    [DataType(DataType.Date)]
    public DateTime RequestDate { get; set; }

EDIT:

   [HttpGet]
    public ActionResult DispatchResponseIndex()
    {
        DispatchResponseModel model = new DispatchResponseModel();       


        //if the users session id isnt null then we know they have data related to this form
        object UserID = Session["TestID"];
        if (UserID == null)
        {
            return View(model); //default view               
        }
        else
        {
            UserID = Session["TestID"];
        }

        LoadDB(model, (Guid)UserID);
     //looking at the model here the RequestDate has a valid date of  //{5/24/2013 12:00:00 AM}

        return View(model); 
    }

EDIT 2:

If I use @Html.TextBox("asdasd",Model.RequestDate); Then it will display the saved date in string format, but I need to use the built in date editor for the text box.

tereško
  • 58,060
  • 25
  • 98
  • 150
John Edwards
  • 1,536
  • 3
  • 14
  • 33

8 Answers8

28

This does seem to cause a lot of confusion and it annoyed me!

If you use DataType.Date you need to set it like this:

[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]

Chrome's date picker uses the local computer's short date format. Even setting the lang tag is ignored; here is an example using Chrome and <html lang="en-GB">:

enter image description here

Chrome's date picker also uses the local computer's locale. On page load, the date will be populated (if set) and the user can select a new date:

enter image description here

Note: If you change the computer's locale you must restart Chrome completely to see the locale change.

plr108
  • 1,201
  • 11
  • 16
Piotr Kula
  • 9,597
  • 8
  • 59
  • 85
  • 1
    Sadly, this solution also affects DisplayFor(), so all your dates will display in this international format. – Dave_cz Dec 23 '15 at 21:09
16

FINAL

I'm an idiot. I had no idea Chrome had a date picker that it added. I thought it was something built into MVC. I need to use an actual jquery date picker. Thanks everyone for all the info.

John Edwards
  • 1,536
  • 3
  • 14
  • 33
  • 3
    You're not the only one, just happened to me and this comment helped me realize it. – Maxito Jun 09 '14 at 21:36
  • 2
    Its HTML5 Datepicker which each HTML5 browser implements its self. Differently for Mobile and Desktop too, so its native to the platform and set the the locale properly. It took me a while to work out what was going on with this too. But once you know, your the boss. – Piotr Kula Apr 20 '15 at 17:29
3

Add Format line in you model

[Display(Name = "Time")]        
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM/dd/yyyy}")]
[DataType(DataType.Date)]
public DateTime RequestDate { get; set; }

Update

OR

Can you change the model property datetime to string. and convert your datetime object to string !!

OR

Or you can format that value in your editor field .for sample like

@Html.TextBoxFor(model => model.FromDate, "{0:d}")
  • 3
    I tried this, and it still just displays "mm/dd/yyyy".It is getting very peculiar. I am using [DataType(DataType.Date)] so I can have the built in date editor. – John Edwards May 30 '13 at 19:05
  • Can you change the model property datetime to string. and convert your datetime object to string !! –  May 30 '13 at 19:15
  • So you want me to say "public String RequestDate { get; set; }"?Because that removes the date editor. – John Edwards May 30 '13 at 19:24
  • Yes . Or you can format that value in your editor field .for sample like @Html.TextBoxFor(model => model.FromDate, "{0:d}") –  May 30 '13 at 19:26
  • Hm, I tried @Html.TextBoxFor(model => model.RequestDate, "{0:d}" and it displays a date, but there is no longer any date dropdown for that text box. – John Edwards May 30 '13 at 19:33
  • Hey that's a sample format. Now you use this {0:MM/dd/yyyy} instead of {0:d} –  May 30 '13 at 19:35
  • @Html.TextBoxFor(model => model.RequestDate, "{0:MM/dd/yyyy}") Still doesn't display the date picker:( – John Edwards May 30 '13 at 19:41
  • See this blog. It's explain more detail's http://blogs.msdn.com/b/stuartleeks/archive/2011/01/25/asp-net-mvc-3-integrating-with-the-jquery-ui-date-picker-and-adding-a-jquery-validate-date-range-validator.aspx –  May 30 '13 at 19:43
2

Actually until I saw this post, I didn't realise there's "date picker" difference between Chrome and IE, even though I got the sample page layout from the MVC's tutorial.

For someone who doesn't realise the difference, as I did before, please find below the comparison:

enter image description here

karl li
  • 1,316
  • 15
  • 19
2

DataFormatString MUST be EXACT like this "{0:yyyy-MM-dd}" then and only then @Html.EditorFor works with date picker control.

Victor
  • 29
  • 2
1

I had this exact same problem. If you look at the HTTP Post that was going back to the Controller and the format of the date in the POST it is yyyy-MM-dd.

I changed my data annotation to this and it worked ... Except now the Index list view shows yyyy-mm-dd format. And the Edit shows mm/mm/yyyy in a datepicker control?

Added to Model Date -

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

IMHO EVERY app I've seen since 1980 has used dates and times. Why is this still a mess Mr MS?

slfan
  • 8,950
  • 115
  • 65
  • 78
Mark
  • 11
  • 1
1

This is how i do it inside the model

[Display(Name = "Effective Date")]
    [DataType(DataType.Date)]
    [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd-MMM-yyyy}")]
    public DateTime? Effectivedate 
    {
        get { return EffectivedateEdit; }
        set { EffectivedateEdit = value; EffectivedateEdit = value; } 
    }


    [DataType(DataType.Date)]
    [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:yyyy-MM-dd}")]
    public DateTime? EffectivedateEdit { get; set; }
Robert
  • 5,278
  • 43
  • 65
  • 115
0

It also take me about 5days to find out how make it done, so may be help someome

first in Model you should have line : [DataType(DataType.Date)]

Then in View, you shoud user @Html.TextBoxFor instead of @Html.EditorFor

enter 

    [DataType(DataType.Date)]
    public DateTime Expireddate { get; set; }

code here

inview as below:

enter  <td>

                  
                    @Html.TextBoxFor(modelItem => item.Expireddate.Date, "{0:yyyy-MM-dd}",

                  new
                  {
                      onkeydown = "return  event.keyCode != 13",
                      @class = "form-control datepicker",
                      @type = "date",
                      @value = ToolShare.datetoStringyyyymmddviewnet(@item.Expireddate.Date),
                      id = @item.id,
                      onChange = "replaceContentsOfDivupdateExpireddate(this.id, this.value)"

                  })


                    @Html.ValidationMessageFor(modelItem => item.Expireddate)
                </td>

code here

function datetoStringyyyymmddviewnet to convert datetime to string like : yyyy-mm-dd

enter  public static String datetoStringyyyymmddviewnet(DateTime datevalue)
    {

        // yyyy-mm-dd  to date

       

        return datevalue.Year +"-" + datevalue.Month +"-"+ datevalue.Day;
    }

code here

Truong Mai Van
  • 137
  • 1
  • 4