我认为根本问题是 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小部件的数据。