Assign DateTime format as data annotations?

I have this attribute in my view model:

[DataType(DataType.DateTime)] public DateTime? StartDate { get; set; } 

If I want to display a date or fill in a date text field, I have the following data:

 <%: Model.StartDate %> <%: Html.TextBoxFor(m => m.StartDate) %> 

Whenever a date is displayed, it is displayed as follows: 01/01/2011 12:00:00 AM

But I would like to show only 01/01/2011

Is there a way to apply a display format with data annotations? I do not want every time I show the date, add code to format it.

+87
c # asp.net-mvc data-annotations
Mar 09 '11 at 10:22
source share
10 answers

Try tagging it:

 [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM/dd/yyyy}")] 
+137
Mar 09 '11 at 22:27
source share

Have you tried this?

 [DataType(DataType.Date)] 
+38
Jul 30 2018-11-11T00:
source share

In mvc 4, you can easily do this, as after using TextBoxFor ..

 @Html.TextBoxFor(m => m.StartDate, "{0:MM/dd/yyyy}", new { @class = "form-control default-date-picker" }) 

This way you do not need to use data annotation in the model or view model class

+22
Mar 23 '15 at 20:13
source share

If your data field is already a DateTime data type, you do not need to use [DataType(DataType.Date)] for annotation; just use:

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

in jQuery, use datepicker for your calendar

  $(document).ready(function () { $('#StartDate').datepicker(); }); 

on your HTML, use EditorFor helper:

  @Html.EditorFor(model => model.StartDate) 
+18
Oct 07 '15 at 16:59
source share

Apply DataAnnotation as:

 [DisplayFormat(DataFormatString = "{0:MMM dd, yyyy}")] 
+14
Mar 22 '14 at 12:02
source share

Use this, but this is the complete solution:

 [DataType(DataType.Date)] [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}")] 
+9
Sep 05 '15 at 16:01
source share

Use EditorFor instead of TextBoxFor

+4
Jul 19 '13 at 16:02
source share

After comments

  // [DataType(DataType.DateTime)] 

Use the data annotation attribute:

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

STEP-7 of the following link can help you ...

http://ilyasmamunbd.blogspot.com/2014/12/jquery-datepicker-in-aspnet-mvc-5.html

+4
Apr 11 '15 at 10:33
source share

set your property using the code below during model creation. I think your problem will be solved. And the time is not displayed in the database. You do not need to add any annotations.

 private DateTime? dob; public DateTime? DOB { get { if (dob != null) { return dob.Value.Date; } else { return null; } } set { dob = value; } } 
0
Jul 31 '15 at 7:51
source share

It suits me

 [DataType(DataType.DateTime)] [DisplayFormat(DataFormatString = "{0:dd-mm-yyyy}", ApplyFormatInEditMode = true)] 
0
Jun 05 '19 at 3:23
source share



All Articles