Mohammad Shadmehr
Mohammad Shadmehr

Reputation: 695

ASP.NET MVC Core DateTime format using jQuery DateTimePicker

I have an ASP.NET Core MVC application with a view model which has a DateTime property for "Date of Birth":

[Required]
public DateTime DateOfBirth { get; set; }

I want to let the user to pick/enter date in dd/mm/yyyy format.

In the view originally I was using html Date type and it was working fine in Chrome but some issues in Edge and not working in IE 11 at all. Therefore I have decided to replace it with the jQuery DatePicker:

<input class="form-control datepicker" name="DateOfBirth" type="text" required>

In Js file:

$(".datepicker").datepicker({ dateFormat: 'dd/mm/yy' });

It all works fine as long as I pass value as mm/dd/yyyy format (12/12/2017). As soon as I change it to 13/12/2017 (dd/mm/yyyy) I get server side error saying that method arguments are not valid.

Upvotes: 1

Views: 4811

Answers (2)

Emrah AKIN
Emrah AKIN

Reputation: 173

<input class="form-control datepicker" name="DateOfBirth" type="text" required data-date-format="dd-mm-yyyy">

You must use date-date-format:"dd-mm-yyyy"

Upvotes: 1

user3559349
user3559349

Reputation:

You need to set the culture of your server to one that accepts dates in dd/MM/yyyy format.

To set the default culture in your startup.cs file, in the ConfigureServices method (note the following sets the culture to en-AU (Australia))

public void ConfigureServices(IServiceCollection services)
{
    services.Configure<RequestLocalizationOptions>(options =>
    {
        options.DefaultRequestCulture = new RequestCulture("en-AU");
    });
    services.AddMvc();
}

and in the Configure method

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

Upvotes: 0

Related Questions