Wrong DateFormat with Jquery Datepicker

前端 未结 1 1329
离开以前
离开以前 2020-12-21 21:37

I want to exclude the time part in the DateTime Textbox, but I can\'t make it work the way I want.

This is how I set up the field :

@H         


        
1条回答
  •  渐次进展
    2020-12-21 22:06

    The reason why you date is not being correctly bound is that your datepicker is using dd/MM/yyy format, but you server is using MM/dd/yyyy format. To make this work, you can create a custom model binder to handle DateTime values and parse them to the format you want.

    public class CustomDateTimeBinder : IModelBinder
    {
      public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
      {
        var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
        CultureInfo culture = new CultureInfo("en-GB"); // dd/MM/yyyy
        var date = value.ConvertTo(typeof(DateTime), culture);
        return date;
      }
    }
    

    and register it in Global.asax (this means it will apply to all DateTime values

    ModelBinders.Binders.Add(typeof(DateTime), new YourAssembly.CustomDateTimeBinder());
    

    0 讨论(0)
提交回复
热议问题