MVC3 & Razor - Change DateTime String from "mm/dd/yyyy 12:00:00 AM" to "mm/dd/yyy" in a Textbox

Timothy Green picture Timothy Green · Feb 12, 2011 · Viewed 29.2k times · Source

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

Answer

Darin Dimitrov picture Darin Dimitrov · Feb 12, 2011

I would use an editor template and data annotations on the view model to specify formatting which makes the views much cleaner:

[DataType(DataType.Date)]
[DisplayName("Birthday:")]
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
public DateTime? Birthday { get; set; }

and then inside your view:

<span class="datePicker">
    @Html.LabelFor(x => x.Birthday)
    @Html.EditorFor(x => x.Birthday)
</span>

and then adapt the selector because the textbox will no longer have the datePicker class:

$('.datePicker :text').datepicker({ 
    showOn: 'both', 
    buttonImage: "/content/images/calendar-red.gif" 
});