0

My date is displayed like dd/mm/yyyy. I want it displayed like yyyy-mm-dd.

 @Html.EditorFor(x=> x.DateChosen, new { htmlAttributes = new { @id = "choosetime" } })

I already tried

  @Html.EditorFor(x=> x.DateChosen, new { htmlAttributes = new { @id =     "choosetime", "{0:dd/MM/yyyy}" } })
codeislife
  • 223
  • 1
  • 2
  • 8

1 Answers1

0

What you are looking for is DisplayFormatAttribute :

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

    // Other properties goes there
}

And use your Html helper like this :

 @Html.EditorFor(x=> x.DateChosen, new { htmlAttributes = new { @id = "choosetime" } })

Edit 1 :

Base on comment, if you need to access the string representation of the DateChosen property somewhere else in your code, you can update your model like that :

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

    public string DateChosenString
    {
        return DateChosen.ToString("yyyy-MM-dd");
    }     

    // Other properties goes there
}
Fabien ESCOFFIER
  • 4,751
  • 1
  • 20
  • 32
  • Just look at my comment @codeislife this is a duplicate – JDupont Apr 14 '16 at 20:30
  • This work, tested locally, can you update your question with the full code of your model and how you are using your html helper ? – Fabien ESCOFFIER Apr 14 '16 at 20:33
  • You should specify ApplyFormatInEditMode = true, because it's that telling the Html helper to apply this format when rendering the textbox. – Fabien ESCOFFIER Apr 14 '16 at 20:37
  • Instead of DateTime type, I am using a type String. Can that be the problem? – codeislife Apr 14 '16 at 21:29
  • It's that. You don't use DateTime for a special reason ? – Fabien ESCOFFIER Apr 14 '16 at 21:31
  • Yes. I need it for a string somewhere else in my code. Is there another way? Can I convert it to the yyyy-mm-dd form there by any chance?@Html.EditorFor(x=> x.DateChosen, new { htmlAttributes = new { @id = "choosetime" } }) – codeislife Apr 14 '16 at 21:43
  • Thanks so much. Now I am getting that the ToString("yyyy-MM-dd") has invalid arguments. – codeislife Apr 14 '16 at 21:53
  • Hum, it work perfectly on my machine, Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd")) give me 2016-04-15. You can check this overload of the ToString method on MSDN https://msdn.microsoft.com/fr-fr/library/zdtaw1bw(v=vs.110).aspx. Can you please paste your model code ? – Fabien ESCOFFIER Apr 14 '16 at 21:56