ZVenue ZVenue - 1 year ago 85
C# Question

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.

Answer Source

If the column type is DateTime in SQL then it will store a time where you pass one or not.

It'd be better to save the date properly:

model.ReturnDate = DateTime.Now;

and then format it when you need to display it:


Or if you're using EditorFor:

@Html.EditorFor(model => model.ReturnDate.ToShortDateString())


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

To add a property to your model add this code:

public string ReturnDateForDisplay
       return this.ReturnDate.ToString("d");

Then in your PartialView:

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


Hi guys, just want to clarify for this answer that by my saying 'If you're using EditorFor', that means you need to have an EditorFor template for the type of value you're trying to represent.

Editor templates are a cool way of managing repetitive controls in MVC:


You can use them for naive types like String as I've done above; but they're especially great for letting you template a set of input fields for a more complicated data type.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download