17

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.

15
  • add your action to see what's happening Commented May 30, 2013 at 18:31
  • Could you elaborate a little? I have been using MVC for a week. I set the RequestDate in my controller and passed it into the view. Is this not enough? Commented May 30, 2013 at 18:32
  • it should be enough but, check in your model you have and what annotation you added it could be something with the DisplayFormat Commented May 30, 2013 at 18:35
  • 1
    Ah I think it may be because its a date and not a datetime/ Commented May 30, 2013 at 18:37
  • Can you show us how you're passing the model to your View? Just to rule out any errors there Commented May 30, 2013 at 18:39

8 Answers 8

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Sadly, this solution also affects DisplayFor(), so all your dates will display in this international format.
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.

2 Comments

You're not the only one, just happened to me and this comment helped me realize it.
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.
4

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}")

8 Comments

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.
Can you change the model property datetime to string. and convert your datetime object to string !!
So you want me to say "public String RequestDate { get; set; }"?Because that removes the date editor.
Yes . Or you can format that value in your editor field .for sample like @Html.TextBoxFor(model => model.FromDate, "{0:d}")
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.
|
2

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?

Comments

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

Comments

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; }

Comments

1

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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.