Wreigh Christian Santos Wreigh Christian Santos - 4 months ago 37
jQuery Question

Datepicker setData displays incorrect date on dateFormat 'MM yy'

I'm working with a datepicker that only needs to show and pick the month and the year. So I changed the dateFormat to 'MM yy'. Now when I do:

$('.date-picker').datepicker('setDate', 'July 2016');


The datepicker shows January 2022. But when I do:

console.log($('.date-picker').datepicker("getDate"));


It shows Tue Jul 19 2016 00:00:00 GMT+0800 (PHT)

I tried changing the dateFormat to 'MM dd yy' and setDate to 'July 01 2016' and it works smoothly.

Here is the JSFiddle: http://jsfiddle.net/gaddygs3/3/

Thanks!

Answer
$(document).ready(function() {
$('#txtDate').datepicker({
 changeMonth: true,
 changeYear: true,
 dateFormat: 'MM yy',

 onClose: function() {
    var iMonth = $("#ui-datepicker-div .ui-datepicker-month :selected").val();
    var iYear = $("#ui-datepicker-div .ui-datepicker-year :selected").val();
    $(this).datepicker('setDate', new Date(iYear, iMonth, 1));
 },

 beforeShow: function() {
   if ((selDate = $(this).val()).length > 0) 
   {
      iYear = selDate.substring(selDate.length - 4, selDate.length);
      iMonth = jQuery.inArray(selDate.substring(0, selDate.length - 5), $(this).datepicker('option', 'monthNames'));
      $(this).datepicker('option', 'defaultDate', new Date(iYear, iMonth, 1));
       $(this).datepicker('setDate', new Date(iYear, iMonth, 1));
   }
}
});
});

Check here

Comments