Display only date and no time

C#asp.net Mvcasp.net Mvc-3Datetime

C# Problem Overview


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..

EDIT:

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.

C# Solutions


Solution 1 - C#

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:

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

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

Sorry if this answer is a little late ;)

Solution 2 - C#

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:

@Html.Label(Model.ReturnDate.ToShortDateString())

Or if you're using EditorFor:

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

or

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

To add a property to your model add this code:

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

Then in your PartialView:

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

EDIT:

I 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:

http://coding-in.net/asp-net-mvc-3-how-to-use-editortemplates/

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.

Solution 3 - C#

This works if you want to display in a TextBox:

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

Solution 4 - C#

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...

Solution 5 - C#

You can modify your ViewModel as below:

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

Solution 6 - C#

You can apply custom date time format using ToString like:

DateTime.Now.Date.ToString("MM/dd/yyyy");

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"))

Solution 7 - C#

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.

<table>
  <tr>
   <th>Type</th>
   <th>Start Date</th>
  </tr>
    @foreach (var item in Model.TestList) {
      <tr>
        <td>@item.TypeName</td>
        <td>@item.StartDate.Value.ToShortDateString()</td>
      </tr>
      }
</table>

Solution 8 - C#

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.

Solution 9 - C#

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

Solution 10 - C#

You could simply convert the datetime. Something like:

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

Solution 11 - C#

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionZVenueView Question on Stackoverflow
Solution 1 - C#Lazy DaveView Answer on Stackoverflow
Solution 2 - C#Russ ClarkeView Answer on Stackoverflow
Solution 3 - C#BrijView Answer on Stackoverflow
Solution 4 - C#Jon SkeetView Answer on Stackoverflow
Solution 5 - C#Ishant SitaulaView Answer on Stackoverflow
Solution 6 - C#Jalal SaidView Answer on Stackoverflow
Solution 7 - C#ApolloView Answer on Stackoverflow
Solution 8 - C#j.rmz87View Answer on Stackoverflow
Solution 9 - C#Pradip RupareliyaView Answer on Stackoverflow
Solution 10 - C#ANJYRView Answer on Stackoverflow
Solution 11 - C#LeeView Answer on Stackoverflow