problem in converting date in fromat : dd.MM.yyyy to MM/dd/yyyy in mvc
Following is the example
Model
public class MyViewModel
{
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd.MM.yyyy}")]
public DateTime Validity { get; set; }
}
Controller
public class HomeController : Controller
{
public ActionResult Index()
{
return View(new MyViewModel
{
Validity = DateTime.Now
});
}
[HttpPost]
public ActionResult Index(MyViewModel model)
{
return View(model);
}
}
View
@model MyViewModel
@using (Html.BeginForm())
{
@Html.EditorFor(x => x.Validity)
<input type="submit" value="OK" />
}
When I select a date like 12.12.2011 it is working fine but When i use a date lik开发者_如何学运维e 18.12.2011 it sets the value in the property(datetime) to 01/01/0001. This is a problem for me.
You're expecting dates in "UK" format (day/month/year) but the conversion code is using "US" format (month/day/year).
The code that converts from a string to a DateTime
needs to use the correct format string.
You need the DateTime.Parse
method that takes culture and formatting information. You can give this method a list of possible formats so you can cope with a variety of inputs.
You can add <globalization uiCulture="en-GB" culture="en-GB" />
in web.config file.
精彩评论