[c#] Display only date and no time

In MVC razor, I am putting current date in the database like this..

model.Returndate = DateTime.Now.Date.ToShortDateString();

Since the database field is a datetime datatype and I am converting the current date to string format, this is not working.. how can I do this? I am doing the string format because I want the date in mm/dd/yyyy format and not in mm/dd/yyyy hh:mm:ss time format..


In the controller I have

var model = new ViewModel();
model.ReturnDate = DateTime.Now;            
return PartialView("PartialView", model);  

In the partialview, I have

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

This is where its displaying the date as Date and Time together... I want just the date to be displayed. Not the time. I hope this edit explains better.

This question is related to c# asp.net-mvc asp.net-mvc-3 datetime

The answer is

Include Data Annotations like DisplayFormat and ApplyFormatInEditMode to have the desired output.

[Display(Name = "Bill Date")] [DataType(DataType.Date)] [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)] public DateTime BillDate { get; set; }

Now your Bill date will show like.

enter image description here

You can modify your ViewModel as below:

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

Just had to deal with this scenario myself - found a really easy way to do this, simply annotate your property in the model like this:

public DateTime? SomeDateProperty { get; set; }

It will hide the time button from the date picker too.

Sorry if this answer is a little late ;)

If you have a for loop such as the one below.

Change @item.StartDate to @item.StartDate.Value.ToShortDateString()

This will remove the time just in case you can't annotate your property in the model like in my case.

   <th>Start Date</th>
    @foreach (var item in Model.TestList) {

I had some problems with the other solutions on this page, so thought I'd drop this in.

@Html.TextBoxFor(m => m.EndDate, "{0:d}", new { @class = "form-control datepicker" })

So you only need to add "{0:d}" in the second parameter and you should be good to go.

This works if you want to display in a TextBox:

@Html.TextBoxFor(m => m.Employee.DOB, "{0:dd-MM-yyyy}")

You could simply convert the datetime. Something like:

@Convert.ToString(string.Format("{0:dd/MM/yyyy}", Model.Returndate))

The date/time in the datebase won't be a formatted version at all. It'll just be the date/time itself. How you display that date/time when you extract the value from the database is a different matter. I strongly suspect you really just want:

model.Returndate = DateTime.Now.Date;

or possibly

model.Returndate = DateTime.UtcNow.Date;

Yes, if you look at the database using SQL Server Studio or whatever, you'll now see midnight - but that's irrelevant, and when you fetch the date out of the database and display it to a user, then you can apply the relevant format.

EDIT: In regard to your edited question, the problem isn't with the model - it's how you specify the view. You should use something like:

@Html.EditorFor(model => model.Returndate.Date.ToString("d"))

where d is the standard date and time format specifier for the short date pattern (which means it'll take the current cultural settings into account).

That's the bit I've been saying repeatedly - that when you display the date/time to the user, that's the time to format it as a date without a time.

EDIT: If this doesn't work, there should be a way of decorating the model or view with a format string - or something like that. I'm not really an MVC person, but it feels like there ought to be a good way of doing this declaratively...

I am not sure in Razor but in ASPX you do:

 <%if (item.Modify_Date != null)
     <%=Html.Encode(String.Format("{0:D}", item.Modify_Date))%>     
<%} %>

There must be something similar in Razor. Hopefully this will help someone.

You can apply custom date time format using ToString like:


Further reading on DateTime.ToString formats pattern can be found here and here.

Edit: After your question edit, Just like what other suggested you should apply the date format at your view:

model.Returndate = DateTime.Now.Date;

@Html.EditorFor(model => model.Returndate.Date.ToString("MM/dd/yyyy"))

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-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= 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 asp.net-mvc-3

Better solution without exluding fields from Binding IIs Error: Application Codebehind=“Global.asax.cs” Inherits=“nadeem.MvcApplication” Can we pass model as a parameter in RedirectToAction? return error message with actionResult Why is this error, 'Sequence contains no elements', happening? Failed to load resource: the server responded with a status of 500 (Internal Server Error) in Bind function 500.19 - Internal Server Error - The requested page cannot be accessed because the related configuration data for the page is invalid String MinLength and MaxLength validation don't work (asp.net mvc) How to set the value of a hidden field from a controller in mvc How to set a CheckBox by default Checked in ASP.Net MVC

Examples related to datetime

Comparing two joda DateTime instances How to format DateTime in Flutter , How to get current time in flutter? How do I convert 2018-04-10T04:00:00.000Z string to DateTime? How to get current local date and time in Kotlin Converting unix time into date-time via excel Convert python datetime to timestamp in milliseconds SQL Server date format yyyymmdd Laravel Carbon subtract days from current date Check if date is a valid one Why is ZoneOffset.UTC != ZoneId.of("UTC")?