0

For some reason the date format is not passing to my view, I have used the following in my model:-

using System.ComponentModel.DataAnnotations;

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

then in my view

@model.Date

and the output in the browser is

20/11/2013 00:00:00

it always adds the "00:00:00" even though time is not on the sql field and ive applied formatting to it.

does anyone know whats up?

Thanks

tereško
  • 58,060
  • 25
  • 98
  • 150
AlexW
  • 2,843
  • 12
  • 74
  • 156
  • The DateTime type always has a time element,even if it's 0. You'll have to change the display format on the View. – Panagiotis Kanavos Jan 13 '14 at 15:48
  • @Alex in your view, are you using the HtmlHelper or just emitting the model field directly? The data annotations don't automatically work, they are there as a hint to the HtmlHelper methods. – Michael Edenfield Mar 10 '14 at 14:45

2 Answers2

2

Try

@model.Date.Value.ToString("dd/MM/yyyy")

brothers28
  • 1,196
  • 17
  • 23
  • I get "No overload to string takes 1 arguments"? – AlexW Jan 14 '14 at 09:29
  • Oh I'm sorry... Because your Date is nullable you have to add .Value So your View should be like @Model.Date.Value.ToString("dd/MM/yyyy")" But be careful! If you have a null in your Date variable and you call a ToString() on it you will get an error... – brothers28 Jan 14 '14 at 10:24
  • You also won't need [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)] in your class anymore – brothers28 Jan 14 '14 at 10:28
0

@model.Date just calls a ToString() on that property, and that uses the formatting settings according to the current culture.

The [DisplayFormat] attribute is used by the MVC model binding methods, such as Display()/DisplayFor() and Editor()/EditorFor().

fejesjoco
  • 11,763
  • 3
  • 35
  • 65