Austin Harris
Austin Harris

Reputation: 5410

MVC DateTime Textbox Formatting Issue

I would like to do something like

model.PickupDate.ToString("d")

But MVC4 is not liking that very much. PickupDate is a DateTime field and I would like to strip off the time portion when displayed in the view, while keeping the new { id = "date1" } code which binds the TextBoxFor to the javasript datepicker. How can I display the Date portion only in this instance?

@Html.TextBoxFor(model => model.PickupDate, new { id = "date1" })

Upvotes: 20

Views: 48753

Answers (7)

manoj kumar
manoj kumar

Reputation: 51

   @Html.TextBoxFor(model => model.Date, String.Format("{0:dddd, MMMM d, yyyy}",Model.Date),  new { @class = "form-control"})

Upvotes: 0

CrnaStena
CrnaStena

Reputation: 3157

Display will depend on culture. And while in most cases all other answers are correct, it did not work for me. Culture issue will also cause different problems with jQuery datepicker, if attached.

If you wish to force the format escape / in the following manner:

@Html.TextBoxFor(model => model.PickupDate, "{0:MM\\/dd\\/yyyy}", new { id = "date1" })

If not escaped for me it show 08-01-2010 vs. expected 08/01/2010.

Also if not escaped jQuery datepicker will select different defaultDate, in my instance it was May 10, 2012.

Upvotes: 0

Yiding
Yiding

Reputation: 2944

This should work:

@Html.TextBoxFor(model => model.SomeDateTime, "{0:MM/dd/yyyy}", new { id = "yourID" })

Upvotes: 28

D.Rosado
D.Rosado

Reputation: 5773

Based on https://stackoverflow.com/a/13702321/787511, tested with JQueryUI datepicker.

@Html.TextBoxFor(model => model.PickupDate, "{0:d}", new { id = "date1" })

Upvotes: 4

Kenneth Garza
Kenneth Garza

Reputation: 1916

this is how I would do this. Hope it helps

 @Html.TextBoxFor(m => m.MyDateTime, new { Value = Model.MyDateTime.ToString("MM-dd-yyyy"), id = "MySuperCoolId"});

or in your case

@Html.TextBoxFor(m => m.PickupDated, new { Value = Model.PickupDate.ToString("d"), id = "date1"});

Upvotes: 30

Lotok
Lotok

Reputation: 4607

Where you define your model you can supply the date formatting, in this example I have DD/MM/YYYY as my format, but you can do whatever format you need.

Model Code

public class MyModel
{
   [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
   public DateTime SomeDateTime {get;set;}
}

Then your razor

@Html.EditorFor(model => model.SomeDateTime, new { id = "date1" })

Upvotes: 4

Elvin Mammadov
Elvin Mammadov

Reputation: 27387

If you make conversion only on the View, you can write this as follow

@Html.TextBoxFor(model => model.SomeDateTime, String.Format("{0:MM/dd/yyyy}"))

Upvotes: 0

Related Questions