问题
I've added a jQuery Datepicker to an EditFor with a POCO model. But I’m having a weird behaviour in the browser when I select a date in the DatePicker: the textbox presents the date in this format: "dd/MM/yyyyyyyy" Here a sample code that reproduces that: The Person model:
public class PersonModel
{
public string PersonID { get; set; }
public string Nombre { get; set; }
[DataType(DataType.Date)]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}")]
public DateTime DoB { get; set; }
}
The view:
<div class="form-group">
@Html.LabelFor(model => model.Nombre, new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Nombre)
@Html.ValidationMessageFor(model => model.Nombre)
</div>
</div>
The DateTime.cshtml view
@model System.DateTime
@Html.TextBox("", ViewData.TemplateInfo.FormattedModelValue,
new { data_datepicker = true });
The test.js
$(document).ready(function () {
$('#DoB').datepicker({
dateFormat: "dd/mm/yyyy"
});
});
The Create Action that sends the model to the view
public ActionResult Create()
{
var person = new PersonModel();
person.PersonID = Guid.NewGuid().ToString();
person.DoB = DateTime.Today.AddYears(-30);
return View(person);
}
All css and js files are added in the BundleCondig.cs file. Thanks for your help.
回答1:
datepicker date format is:
dateFormat: "dd/mm/yy"
http://jqueryui.com/resources/demos/datepicker/date-formats.html
回答2:
The jQuery UI Datepicker format for a four-digit year should be just two ys. I think the Datepicker control is reformatting the value of the input that was rendered by your MVC view. Try this:
$('#DoB').datepicker({
dateFormat: "dd/mm/yy"
});
Try it out:
console.log($.datepicker.formatDate('dd/mm/yy', new Date()));
// 10/06/2014
console.log($.datepicker.formatDate('dd/mm/yyyy', new Date()));
// 10/06/20142014
回答3:
Try this :
$(document).ready(function () {
$('#DoB').datepicker({
dateFormat: 'm/d/yy'
});
});
来源:https://stackoverflow.com/questions/24149024/mvc-jquery-datepicker-returns-dd-mm-yyyyyyyy