ASP.NET MVC3 - DateTime format

33,262

Solution 1

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());

Solution 2

Based upon your comment I see all you want is an english current but with a different date format (Correct me if I'm wrong).

The fact is the DefaultModelBinder uses the culture settings of the server for form data. So I can say the server use "en-US" culture but with a different date format.

You can do something like this in the Application_BeginRequest and you are done!

protected void Application_BeginRequest()
{
    CultureInfo info = new CultureInfo(System.Threading.Thread.CurrentThread.CurrentCulture.ToString());
    info.DateTimeFormat.ShortDatePattern = "dd.MM.yyyy";
    System.Threading.Thread.CurrentThread.CurrentCulture = info;
}

Web.Config

<globalization culture="en-US" />
Share:
33,262
šljaker
Author by

šljaker

do { coding; } while (!endOfLife);

Updated on August 17, 2020

Comments

  • šljaker
    šljaker over 3 years

    I'm using ASP.NET MVC 3.
    My ViewModel looks like this:

    public class Foo
    {
        [DataType(DataType.Date)]
        [DisplayFormat(DataFormatString = "{0:dd.MM.yyyy}", ApplyFormatInEditMode = true)]
        public DateTime StartDate { get; set; }
        ...
    }
    

    In view, I have something like this:

    <div class="editor-field">
        @Html.EditorFor(model => model.StartDate)
        <br />
        @Html.ValidationMessageFor(model => model.StartDate)
    </div>
    

    StartDate is displayed in correct format, but when I change it's value to 19.11.2011 and submit the form, I get the following error message: "The value '19.11.2011' is not valid for StartDate."

    Any help would be greatly appreciated!