0

I have a text input on my form which when sent to the server is bound to the DateTime property of my model in the wrong format, it comes out as MM/dd/yyyy instead of dd/MM/yyyy.

The best suggestion I have seen so far is to set the serializer culture as below, however it didn't seem to make a difference.

services.AddMvc()
    .AddJsonOptions(options =>
    {
        options.SerializerSettings.Culture = new CultureInfo("en-GB");
    });

I don't see why I would have to use a custom model binder, this seems like something which should be resolved with culture.

Tsahi Asher
  • 1,767
  • 15
  • 28
JakeAM
  • 161
  • 1
  • 5

2 Answers2

0

If you want to set culture for date binding , you could configure the below settings in the ConfigureServices method :

services.Configure<RequestLocalizationOptions>(options =>
{
            options.DefaultRequestCulture = new RequestCulture("en-GB");
            options.SupportedCultures = new List<CultureInfo> { new CultureInfo("en-GB") };
});
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

Second. Ensure that your call to UseRequestLocalization happens before UseMvc.

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.UseRequestLocalization();
    app.UseMvc();
} 

Reference : https://stackoverflow.com/a/44692569/10201850

Xueli Chen
  • 11,987
  • 3
  • 25
  • 36
  • Appreciate the response. Sadly that didn't fix the issue. The parameter always comes through as null as the datetime is invalid. – JakeAM Aug 15 '19 at 12:13
0

It turns out I was only hitting the issue when the date was passed in the query string. After reading some documentation it turns out that the default culture used for model binding data from the query string is the invariant culture.

I got around this by binding to a string property and then parsing to a second property of datetime as below.

public class MyClass
{
    public string MyDate { get; set; }
    public DateTime? MyDateParsed
    {
        get { return !string.IsNullOrEmpty(MyDate) ? (DateTime?)DateTime.Parse(MyDate) : null; }
    }
}
JakeAM
  • 161
  • 1
  • 5