[c#] 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.

This question is related to c# asp.net asp.net-mvc data-annotations

The answer is


Use this, but it's a complete solution:

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

After Commenting

          // [DataType(DataType.DateTime)] 

Use the Data Annotation Attribute:

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

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

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


Use EditorFor rather than TextBoxFor


If your data field is already a DateTime datatype, you don't need to use [DataType(DataType.Date)] for the annotation; just use:

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

on the jQuery, use datepicker for you calendar

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

on your HTML, use EditorFor helper:

    @Html.EditorFor(model => model.StartDate)

That works for me

[DataType(DataType.DateTime)]
[DisplayFormat(DataFormatString = "{0:dd-MM-yyyy}", ApplyFormatInEditMode = true)]

Try tagging it with:

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

Apply DataAnnotation like:

[DisplayFormat(DataFormatString = "{0:MMM dd, yyyy}")]

Did you try this?

[DataType(DataType.Date)]

In mvc 4 you can easily do it like following using TextBoxFor..

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

So, you don't need to use any data annotation in model or view model class


set your property using below code at the time of model creation i think your problem will be solved..and the time are not appear in database.you dont need to add any annotation.

private DateTime? dob;
        public DateTime? DOB
        {
            get
            {
                if (dob != null)
                {
                    return dob.Value.Date;
                }
                else
                {
                    return null;
                }

            }
            set { dob = value; }
        }

Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to asp.net

RegisterStartupScript from code behind not working when Update Panel is used You must add a reference to assembly 'netstandard, Version=2.0.0.0 No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization How to use log4net in Asp.net core 2.0 Visual Studio 2017 error: Unable to start program, An operation is not legal in the current state How to create roles in ASP.NET Core and assign them to users? How to handle Uncaught (in promise) DOMException: The play() request was interrupted by a call to pause() ASP.NET Core Web API Authentication Could not load file or assembly 'CrystalDecisions.ReportAppServer.CommLayer, Version=13.0.2000.0 WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for jquery

Examples related to asp.net-mvc

Using Lato fonts in my css (@font-face) Better solution without exluding fields from Binding Vue.js get selected option on @change You must add a reference to assembly 'netstandard, Version=2.0.0.0 How to send json data in POST request using C# VS 2017 Metadata file '.dll could not be found The default XML namespace of the project must be the MSBuild XML namespace How to create roles in ASP.NET Core and assign them to users? The model item passed into the dictionary is of type .. but this dictionary requires a model item of type How to use npm with ASP.NET Core

Examples related to data-annotations

How to add "required" attribute to mvc razor viewmodel text input editor ASP.NET MVC: Custom Validation by DataAnnotation Entity Framework code first unique column Why can't I reference System.ComponentModel.DataAnnotations? DataAnnotations validation (Regular Expression) in asp.net mvc 4 - razor view How do I specify the columns and rows of a multiline Editor-For in ASP.MVC? Disable Required validation attribute under certain circumstances Assign format of DateTime with data annotations? displayname attribute vs display attribute Int or Number DataType for DataAnnotation validation attribute