在 jQuery UI DatePicker 中设置日期

setDate in jQuery UI DatePicker

当我将 setDatedateFormat : 'yy-mm' 一起使用时,jQuery UI DatePicker 显示今天的日期,而不是 setDate 中指定的日期。

示例:http://jsfiddle.net/DBpJe/7981/ (edited from )


但是 dateFormat : 'yy-mm-dd' 它显示 setDate 中指定的日期。 示例:http://jsfiddle.net/DBpJe/7982/

如何使 jQuery UI DatePicker 显示 setDate 中指定的日期与 dateFormat : 'yy-mm' ?

找到一篇完全解决这个问题的文章:http://www.jquerybyexample.net/2012/06/show-only-month-and-year-in-jquery-ui.html

工作示例:http://jsfiddle.net/Twisty/xwnoafxd/

基本上你只需要添加 defaultDate 设置。那些捂脸的事情之一。

$(function() {
  var myDate = new Date(2000, 6, 1);
  $('.date-picker').datepicker({
    changeMonth: true,
    changeYear: true,
    showButtonPanel: true,
    dateFormat: 'yy-mm',
    defaultDate: myDate,
    onClose: function(dateText, inst) {
      function isDonePressed() {
        return ($('#ui-datepicker-div').html().indexOf('ui-datepicker-close ui-state-default ui-priority-primary ui-corner-all ui-state-hover') > -1);
      }
      if (isDonePressed()) {
        var month = $("#ui-datepicker-div .ui-datepicker-month :selected").val();
        var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val();
        $(this).datepicker('setDate', new Date(year, month, 1));
        console.log('Done is pressed')
      }
    }
  }).datepicker("setDate", myDate);
});

jQuery UI DatePicker to show month year only找到解决方案
dateFormat : 'yy-mm' 的工作示例:http://jsfiddle.net/DBpJe/8057/

beforeShow : function(input, inst) {

 if ((datestr = $(this).val()).length > 0) {
  year = datestr.substring(0, 4);
  month = datestr.substring(datestr.length-2, datestr.length);

  $(this).datepicker('option', 'defaultDate', new Date(year, month-1, 1));
  $(this).datepicker('setDate', new Date(year, month-1, 1));

 }
}