Search code examples
asp.net-mvc-4bootstrap-datetimepickereonasdan-datetimepicker

Assigning Value to Bootstrap-datetimepicker with Format MM/YYYY Displays Incorrect Year


I am using bootstrap-datetimepicker version 4.17.47 in ASP MVC 4 app.

I have this model property:

public DateTime MonthYear { get; set; }

I assign default value in controller (arbitrary value is just an example actual value is determined through some logic):

model.MonthYear = new DateTime(2017, 3, 1);

I display this in view using datepicker so users can update the value as needed:

@Html.TextBoxFor(model => model.MonthYear, new { @class = "form-control input month-picker" })

Script:

$('.month-picker').datetimepicker({
    format: 'MM/YYYY',
    useCurrent: false,
    toolbarPlacement: 'bottom',
    viewMode: 'months'
});

The problem is the control displays "03/0001" instead of "03/2017".

What am I missing here?


Solution

  • Apparently the problem is that the input is being filled with a DD/MM/YYYY date from server when datetimepicker is expecting only MM/YYYY. Try formating the textbox, like:

    @Html.TextBoxFor(model => model.MonthYear, "{0:MM/yyyy}", new { @class = "form-control input month-picker" })
    

    That should work.