0

我使用 DateTextBox 作为屏幕上的众多控件之一。我在一个地方注册它们,然后在循环中为它们批量设置值,调用它们中set('value', val)的每一个。所有控件都正常运行,只有 DateTextBox 不会接受来自服务器的数据。

最初 java 的日期被序列化为 long(例如 1280959200000),但是当我更改为 ISO 格式(例如“2010-08-04T22:00:00.000+0000”)时,它也不被接受。但两者都是构造函数接受的日期格式new Date()

在输出中,我得到 ISO 格式的日期值:“2013-08-04T22:00:00.000Z”,因此它也应该在输入时被接受。

我可以用 DateTextBox 做什么来使它接受 JavaScript 的 Date 对象支持的所有格式的值,或者可以从我的服务器返回的格式之一?

4

2 回答 2

2

我认为根本问题是 Javascript 内置 Date 对象只接受某些格式,而 Dojo 依赖于该内置行为。在工作中,我们有一个类似的问题,许多遗留的 PHP 代码习惯于以 Mysql 派生的格式(例如YYYY-MM-DD HH:MM:SS)传递日期。

我们当前的解决方法是 subclass dijit/form/DateTextBox,这也让我们可以进行一些 UI 改进。当某些东西试图设置一个还不是Date对象并且看起来像 MySQL 日期时间的值时,此代码会重新形成它以匹配 ISO-8601 并传递它。

自定义版本的 DateTextBox 的 Dojo 1.9 代码:

define([
    "dojo/_base/declare",
    "dojo/_base/lang",
    "dojo/_base/array",
    "dijit/form/DateTextBox"
], function(declare, lang, array, DateTextBox){

    var clazz = declare([DateTextBox], {


        _mysqlStyleExp : /^(\d{4}-\d{2}-\d{2}) (\d{2}:\d{2}:\d{2})$/,

        postMixInProperties: function(){ // change value string to Date object
            this.inherited(arguments);
            this.constraints.datePattern = "yyyy-MM-dd"; // Affects display to user
        },

        _convertMysqlDateToIso: function(value){
            value = lang.trim(value);
            var matches = this._mysqlStyleExp.exec(value);
            if(matches !== null){
                // Put the "T" in the middle and add fractional seconds with UTC
                // timezone

                // If your MySQL dates are NOT in UTC, obviously this will screw things up!                    
                return matches[1] + "T" + matches[2] + ".000Z";
            }else{
                return null;
            }
        },

        _setValueAttr : function(/*Date|String*/ value, /*Boolean?*/ priorityChange, /*String?*/ formattedValue){
            /*
             We want to be slightly more permissive in terms of the strings that can be set in order to support
             older code... But someday it'd be nice to standardize on Date.toJSON, so warn.
             */
            if(typeof(value) === "string"){
                var isoDate = this._convertMysqlDateToIso(value);
                if(isoDate !== null){
                    console.warn("Converting non-ISO date of "+value);
                    value = isoDate;
                }
            }
            this.inherited(arguments);
        }        
    });

    return clazz;
});

请注意,这只影响流入Dojo小部件的数据。

于 2013-10-22T17:49:11.397 回答
0

文档说:

此小部件的值作为 JavaScript 日期对象,仅指定年/月/日。

所以代替这个(我假设你目前正在做):

new dijit.form.DateTextBox({value: "2010-08-04T22:00:00.000+0000"}, domNode);

做这个:

var myDate = new Date("2010-08-04T22:00:00.000+0000");
new dijit.form.DateTextBox({value: myDate}, domNode);
于 2013-10-22T11:59:53.577 回答