Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign format of DateTime with data annotations?

I have this attribute in my view model:

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

If I want to display the date, or populate a textbox with the date, I have these:

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

Whenever the date is displayed, it's displayed like: 01/01/2011 12:00:00 AM

But I'd like to only display 01/01/2011

Is there a way to apply a display format with data annotations? I don't want to have to go to every instance where I display a date, and add some code to format it.

like image 461
Steven Avatar asked Mar 09 '11 22:03

Steven


People also ask

How do you show calendar with data annotation?

To create the View , right click on view folder and then click Add view. Now specify the view name as Index or as you wish, choose create scaffolding template and model class EmpModel. cs and click on Add button.

What is the format of datetime?

For example, the "d" standard format string indicates that a date and time value is to be displayed using a short date pattern. For the invariant culture, this pattern is "MM/dd/yyyy". For the fr-FR culture, it is "dd/MM/yyyy". For the ja-JP culture, it is "yyyy/MM/dd".

What is System ComponentModel DataAnnotations?

Data annotations (available as part of the System. ComponentModel. DataAnnotations namespace) are attributes that can be applied to classes or class members to specify the relationship between classes, describe how the data is to be displayed in the UI, and specify validation rules.


2 Answers

Try tagging it with:

[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM/dd/yyyy}")] 
like image 68
David Fox Avatar answered Sep 28 '22 11:09

David Fox


Did you try this?

[DataType(DataType.Date)] 
like image 32
rk1962 Avatar answered Sep 28 '22 10:09

rk1962