Adding “st, nd, rd, th” to jquery datepicker

后端 未结 8 550
臣服心动
臣服心动 2020-12-11 15:44

How can I add st,nd,rd,th to date format.. i.e. November 19th, or December 2nd, etc.

Currently, I have following code

    $( \"#datepicker\" ).datepi         


        
8条回答
  •  孤街浪徒
    2020-12-11 16:31

    I realise that this is an old question but I thought I'd post my solution in-case anyone having the same problem finds this post. This method doesn't break the selected date when opening the calendar etc. This uses the format d{suffix} M yy i.e. '30th Sep 2013'

    $.datepicker.origParseDate = $.datepicker.parseDate;
    $.datepicker.parseDate = function(format, value, settings) {
      if ( $.isPlainObject(format) && format.hasOwnProperty('parse') && $.isFunction(format.parse) ) {
        return format.parse.call(this, value, settings, $.datepicker.origParseDate);
      } else {
        $.datepicker.origParseDate(format, value, settings);
      }
    };
    $.datepicker.origFormatDate = $.datepicker.formatDate;
    $.datepicker.formatDate = function(format, date, settings) {
      if ( $.isPlainObject(format) && format.hasOwnProperty('format') && $.isFunction(format.format) ) {
        return format.format.call(this, date, settings, $.datepicker.origFormatDate);
      } else {
        $.datepicker.origFormatDate(format, date, settings);
      }
    };
    
    $('.datepicker').datepicker({
      dateFormat: {
        parse: function(value, settings, originalParseDate) {
          value = value.replace(/[a-z][^\s]+/, '');
          return originalParseDate.call(this, 'd M yy', value, settings);
        },
        format: function(date, settings, originalFormatDate) {
          date = originalFormatDate.call(this, 'd M yy', date, settings).split(' ');
          date[0] += (function(n) {
            n = (+n % 100).toString().split('');
            if (n.length > 1 && n.shift() === '1' || +n[0] > 3) {
              return 'th';
            } else {
              return ['th', 'st', 'nd', 'rd'][+n[0]];
            }
          })(date[0]);
          return date.join(' ');
        }
      }
    });
    

提交回复
热议问题