102

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.

John Saunders
  • 160,644
  • 26
  • 247
  • 397
ZVenue
  • 4,967
  • 16
  • 61
  • 92
  • 2
    don't worry about the 00:00:00 (midnight). Just format the output `ToString("mm/dd/yyyy");` to be able to see exactly what you want. – Chase Florell Aug 19 '11 at 16:17
  • 1
    Save the data in the database as `DateTime`. You do the string formatting on the OUTPUT... Only format it to the end viewer. – Chase Florell Aug 19 '11 at 17:09

11 Answers11

146

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

Lazy Dave
  • 1,501
  • 1
  • 9
  • 7
  • 4
    Just what I needed. Excellent! – RealityDysfunction May 18 '13 at 04:41
  • 1
    I had a sitation recently where chrome put funny stuff in when input type is date, part of html5 i think, I wanted to use jquery datepicker instead so I went with DataType.Text - that still allowed me to use formatting cool enough – John Sep 01 '13 at 12:11
  • 3
    No need to apologise for being late, posting answers to old questions can be a great help for people who aren't OP. This is the answer I was looking for as I knew it was possible but couldn't remember how, and you posted it 3 years ago. If anything you are incredibly early. – RyanfaeScotland May 29 '15 at 10:32
  • if the date comes from a database i don't know how this could help... can't figure it out – Antoine Pelletier Nov 16 '16 at 19:10
  • 1
    This isn't working, it says there is no method called ToString or even ToShortDateString() when trying to use it with DisplayFor(modelItem = item.migrationdate.ToShortDateString()) – Nathan McKaskle May 12 '17 at 15:10
  • FYI, it doesn't work with me without date format `[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]` http://stackoverflow.com/questions/14212527/how-to-set-default-value-to-the-inputtype-date – Shady May 22 '17 at 12:12
107

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.

peterh
  • 11,875
  • 18
  • 85
  • 108
Russ Clarke
  • 17,511
  • 4
  • 41
  • 45
  • not sure who downvoted this.. but I am not using the HTML.label to display this.. I am using HTML.EditorFor(model => model.Returndate) how do I format the display in this case... – ZVenue Aug 19 '11 at 16:31
  • That was just an example of how to format your result; I'll update my answer. – Russ Clarke Aug 19 '11 at 16:34
  • I think if the value is *logically* only a date, it's worth storing just the date part as well, even if the time is going to be stripped on display anyway. – Jon Skeet Aug 19 '11 at 16:38
  • The `Label` parameter isn't the date time. – Daniel A. White Aug 19 '11 at 16:57
  • Indeed, but ZVenue didn't actually say how he was displaying it at the point I wrote that snippet, I was simply trying to illustrate how you should save the data intact, and then format it to the way you require when you display it. – Russ Clarke Aug 19 '11 at 17:06
  • 14
    @Russ: the editorfor update you made did not work. Its giving me an error "Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions." – ZVenue Aug 19 '11 at 17:12
  • Please see my Edit to the original post. This should explain better. – ZVenue Aug 19 '11 at 17:16
  • John skeets answer has everything you need, if you do get that template error again, consider making in a get property on your model that returns the formatted date. – Russ Clarke Aug 19 '11 at 17:50
  • @RussC: Yes I am getting that template error.. and I am not sure what you mean by "get property on your model that returns the formatted date".. Appreciate your help. – ZVenue Aug 19 '11 at 18:11
  • 19
    you should remove '@Html.EditorFor(model => model.ReturnDate.ToShortDateString())' from the answer because that does not work. – James Reategui Apr 15 '12 at 18:33
  • Actually it works fine but you have to have implemented an Editor template for the type of value. Here's a handy guide: http://coding-in.net/asp-net-mvc-3-how-to-use-editortemplates/ – Russ Clarke Apr 15 '12 at 23:39
  • Editor templates are cool but unnecessarily complicated here when you can just use a DataType annotation. – mkataja Jan 03 '14 at 12:57
  • @mkataja Yes; but check the dates; this was MVC3; Also, and more relevant; You can use a data *type* annotation, but data format is a different beast; we always knew it was a day time, he just wanted to render it differently. – Russ Clarke Jan 06 '14 at 06:34
  • I was getting the error "Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions." as described above. Converting it to a string and then displaying it in the view worked for me... @{String DateEdited = (string)Convert.ChangeType(item.DateLastEdited.ToShortDateString(), typeof(string));} @DateEdited – Zenacity Aug 23 '16 at 16:00
  • Will this have an Impact on SQL If we are using EF Code first Approach ? – Abdul Hannan Sep 04 '21 at 06:13
43

This works if you want to display in a TextBox:

@Html.TextBoxFor(m => m.Employee.DOB, "{0:dd-MM-yyyy}")
Leigh
  • 28,765
  • 10
  • 55
  • 103
Brij
  • 11,731
  • 22
  • 78
  • 116
  • date will be shown incorrectly if browser has different format in settings than "dd-MM-yyyy", i.e "MM-dd-yyyy" – Oleg Sh Nov 26 '15 at 20:13
17

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

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • 1
    The DateTime.Now.Date still displays the time along with the date. – ZVenue Aug 19 '11 at 16:32
  • 1
    @ZVenue: Displays it where? You should be *storing* a DateTime value, and using a date-only format specifier wherever you're *displaying* the date. The code you've given (setting a property in the model) is presumably for storage, so it doesn't matter that it's got a time of midnight. – Jon Skeet Aug 19 '11 at 16:34
  • Jon's suggesting what I was talking about, saving the date to SQL as it stands; you can then just format your date appropriately when you print it. – Russ Clarke Aug 19 '11 at 16:37
  • Sorry I didnt say what I was doing with that date time .. I am displaying it in a partial view like @Html.EditorFor(model => model.Returndate)..thasts where this is displayed as date and time together... I want just the date to be displayed in this html.editorfor – ZVenue Aug 19 '11 at 17:09
  • Please see my Edit to the original post. This should explain better. – ZVenue Aug 19 '11 at 17:17
  • @ZVenue: Edited the answer... basically it was exactly what I've been saying before: you need to change how you *display* the value, not how you *store* it. – Jon Skeet Aug 19 '11 at 17:33
  • @Russ: It happens sometimes :( – Jon Skeet Aug 19 '11 at 17:49
  • 2
    @Jon:I am getting this error when I used your edit code for html.editorfor...."Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions"....at run time – ZVenue Aug 19 '11 at 18:02
  • @ZVenue: Then you need to look on ASP.NET MVC tutorials for how to apply formatting to values - which isn't really specific to DateTime. I'll have a look too... – Jon Skeet Aug 19 '11 at 18:18
  • @ZVenue: It could well be that DisplayFormatAttribute is what you're after: http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.displayformatattribute.aspx – Jon Skeet Aug 19 '11 at 18:23
  • 1
    @ZVenue: Have a look at this too: http://stackoverflow.com/questions/5033902/textboxfor-mvc3-date-formatting-and-date-validation – Jon Skeet Aug 19 '11 at 18:40
  • "Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions" above html.editorfor won't work – John Sep 01 '13 at 11:48
  • @John: Hmm - not sure then, to be honest. But hopefully the answer at least gives the flavour of what's wrong, even if the MVC-specific bits aren't quite right. – Jon Skeet Sep 01 '13 at 15:33
10

You can modify your ViewModel as below:

[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}",ApplyFormatInEditMode = true)]
Ishant Sitaula
  • 134
  • 1
  • 6
  • This solution also solves the problem of Chrome's datepicker conflict. If you just specify Datatype.Date in Viewmodel, Chrome uses its own version of datepicker in textbox. Thank you! – Katherine Jul 05 '18 at 22:44
7

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"))
Jalal Said
  • 15,906
  • 7
  • 45
  • 68
5

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>
Apollo
  • 1,990
  • 12
  • 44
  • 65
4

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.

j.rmz87
  • 786
  • 1
  • 7
  • 18
4

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

Rohan Rao
  • 2,505
  • 3
  • 19
  • 39
Pradip Rupareliya
  • 545
  • 1
  • 6
  • 18
  • Please have a look at the other answers. Do you think yours is necessary and adds some new quality content to the post? – L. Guthardt Jul 17 '18 at 08:00
2

You could simply convert the datetime. Something like:

@Convert.ToString(string.Format("{0:dd/MM/yyyy}", Model.Returndate))
ANJYR
  • 2,583
  • 6
  • 39
  • 60
  • Thanks @ANJYR, this one did the trick for me. I am using PickADay library for DateTime fields. Maybe that is why any of the other proposed solutions worked in my case. – cvillalobosm Oct 06 '21 at 17:45
2

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.

Lee
  • 21
  • 2