ASP.NET MVC3 – DateTime format

You need to set the proper culture in the globalization element of your web.config file for which dd.MM.yyyy is a valid datetime format:

<globalization culture="...." uiCulture="...." />

For example that’s the default format in german: de-DE.


UPDATE:

According to your requirement in the comments section you want to keep en-US culture of the application but still use a different formats for the dates. This could be achieved by writing a custom model binder:

using System.Web.Mvc;
public class MyDateTimeModelBinder : DefaultModelBinder
{
    public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        var displayFormat = bindingContext.ModelMetadata.DisplayFormatString;
        var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);

        if (!string.IsNullOrEmpty(displayFormat) && value != null)
        {
            DateTime date;
            displayFormat = displayFormat.Replace("{0:", string.Empty).Replace("}", string.Empty);
            // use the format specified in the DisplayFormat attribute to parse the date
            if (DateTime.TryParseExact(value.AttemptedValue, displayFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out date))
            {
                return date;
            }
            else
            {
                bindingContext.ModelState.AddModelError(
                    bindingContext.ModelName, 
                    string.Format("{0} is an invalid date format", value.AttemptedValue)
                );
            }
        }

        return base.BindModel(controllerContext, bindingContext);
    }
}

which you will register in Application_Start:

ModelBinders.Binders.Add(typeof(DateTime), new MyDateTimeModelBinder());

Leave a Comment