I am trying to stop the Time from showing up in a Birthday Text Field that uses DateTime
My Code: (I'm using the Jquery DatePicker)
<label for="birthday">Birthday:</label>
@Html.TextBox("birthday", (Model.Birthday.ToString()), new { @class = "datePicker" })
The Javascript:
$(document).ready(function () {
$('.datePicker').datepicker({ showOn: 'both', buttonImage: "/content/images/calendar-red.gif" });
});
I have the Model setup for the date:
[DataType(DataType.Date)]
public DateTime? Birthday { get; set; }
Still the Text in the Text box displays:
"8/21/2010 12:00:00 AM"
I want Text in the Textbox to diplay as just:
"8/21/2010"
I have tried everything from:
@inherits System.Web.Mvc.WebViewPage<System.DateTime>
but wont let me do that since I am @using a model
Try changing to this:
@Html.TextBox("birthday", (Model.Birthday.Value.ToShortDateString()), new { @class = "datePicker" })
Since your DateTime is
Nullable
you need to do.Value
before you can access theDateTime
methods.When calling
ToString
on aDateTime
it will give you Date + Time. So Instead of callingToString
you want to use eitherToString
with formatting orToShortDateString
.MSDN has the following to say about ToShortDateString
I was actually running into this problem with Razor using MVC 3. I ended up having to create a DateTime Partial Class in Shared/EditorTemplates to get the attributes I needed.
Previously my view was:
@Html.TextBoxWithAttributesFor(m => m.To, new { @class = "text-box", @readonly = "readonly" })
but this kept given me the TimeStamp. Even when I tried .Value.DateTime or any other work around. But my current, working solution is:view:
partial class:
I used this page as a second source: http://buildstarted.com/2010/09/10/overriding-displayfor-and-editorfor-to-create-custom-outputs-for-mvc/
I would use an editor template and data annotations on the view model to specify formatting which makes the views much cleaner:
and then inside your view:
and then adapt the selector because the textbox will no longer have the
datePicker
class:Where you have "Model.Birthday.ToString()" you need to replace it with "Model.Birthday.ToShortDateString()"