0

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 like 18.12.2011 it sets the value in the property(datetime) to 01/01/0001. This is a problem for me.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
Sanjeev
  • 271
  • 1
  • 5
  • 7
  • 1
    @ChrisF, if we don't instruct new users, chances are that we are having this very same conversation in one year time when the numbers will be different. – Darin Dimitrov Apr 20 '11 at 11:34

2 Answers2

0

You can add <globalization uiCulture="en-GB" culture="en-GB" /> in web.config file.

HashCoder
  • 946
  • 1
  • 13
  • 32
0

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.

ChrisF
  • 134,786
  • 31
  • 255
  • 325