ExtJS DateField混淆格式

时间:2012-02-18 15:34:39

标签: javascript datetime date extjs date-format

我使用指定格式的Ext.form.DateField是'd-m-Y',如下所示:

var sellingDate = new Ext.form.DateField({
    fieldLabel : "Selling date",
    width : 180,
    name: 'sellingDate',
    format: 'd-m-Y',
    allowBlank : false
});

我希望此组件在失去焦点后以给定格式自动完成输入值。我的意思是如果我输入文本'040212'( 2012年2月4日,在我的国家,我们使用'dd-mm-YYYY'作为标准日期格式),它必须将该文本显示为'04 -02 -2012' 。
但是当调试DateField的事件“更改”时,我看到解析的Date对象是“Mon 2012年4月2日”。我不知道如何使它像我期望的那样工作。有没有办法从日期字段中获取原始文本,而不是解析的Date对象?你能帮帮我吗? 非常感谢你!

2 个答案:

答案 0 :(得分:1)

这很简单,添加altFormats配置选项:

  

altFormats:String多个日期格式,以“|”分隔尝试的时候   解析用户输入值并且它与定义的格式不匹配

//So in your case, it should be 'dmy'
var sellingDate = new Ext.form.DateField({
    fieldLabel : "Selling date",
    width : 180,
    name: 'sellingDate',
    format: 'd-m-Y',
    altFormats: 'dmy',
    allowBlank : false
});

答案 1 :(得分:0)

无论您指定的格式如何,Ext都会将任何六位数字符串解析为mmddyy。那很不幸: - /

解析日期的逻辑发生在beforeBlur方法Ext.form.field.Date或(Ext.form.DateField ExtJS 3)中。您可以“拦截”该方法并在解析日期之前执行自己的原始值按摩:

Ext.onReady(function (){
  (function (){

    // capture the original method so we can call it later
    var originalBeforeBlur = Ext.form.field.Date.prototype.beforeBlur;

    Ext.override(Ext.form.field.Date, {
      beforeBlur: function (){
        var raw = this.getRawValue(),
            match = raw.match(/^\s*(\d{2})(\d{2})(\d{2})\s*$/);

        // rearrange the date string to match what Ext expects
        if (match){
          raw = match[2] + match[1] + match[3];
        }

        this.setRawValue(raw);
        originalBeforeBlur.call(this);
      }
    });
  })();

  var panel = new Ext.form.FormPanel({
    title: "Enter a Date",
    renderTo: Ext.getBody(),
    items: {
      xtype: "datefield",
      format: "d-m-Y"
    }
  });
});