ASP.NET MVC3 - DateTime format
Asked Answered
L

3

28

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!

Lippe answered 20/10, 2011 at 12:0 Comment(0)
S
43

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());
Stapes answered 20/10, 2011 at 12:44 Comment(7)
But I wan't use the English culture with different datetime format. Is there any workaround?Spleeny
@šljaker, yes there is. You will have to write a custom model binder and manually parse the date parameter using the format you like.Stapes
The globalization Tag is child of the <system.web> Tag.Shroyer
hi, Darin, i have a question,dd/MM/yyyy format works fine in local machine, but our website hosted in another country, it needs MM/dd/yyyy format else it shows validation error The field BeginDate must be a date., how can i make sever to accept dd/MM/yyyy format, will globalization work?, can i add globalization in a View page instead of web.config ?Teresaterese
Can I turn off date validation completely?Peptic
can change at the iis .net globalization setting. change the culture to your corresponding .Jaffa
Is it possible to do this for just a single DateTime field? I have one which needs to be formatted specially, while all others should be formatted as usual.Launderette
B
11

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" />
Bernhard answered 21/6, 2012 at 15:20 Comment(0)
O
0

Added this below code to global.asax.cs file

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;     
}

And added the below to web.config under <system.web>

<globalization culture="en-US">;
Outwork answered 21/10, 2014 at 12:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.