easyui datagrid中datetime字段的显示和增删改查问题
datagrid中datetime字段的异常显示:
使用过easyui datagrid的应该都知道,如果数据库中的字段是datetime类型,绑定在datagrid显式的时候会不正常显示,一般需要借助于formatter来格式化时间格式
{ title: '活动开始时间', field: 'BeginTime', 300, editor: { type: 'datetimebox', options: { required: true }, formatter: function (v) { return Common.DateTimeFormatter(v); } } }
Common.DateTimeFormatter的具体实现如下:
var Common = { //EasyUI用DataGrid用日期格式化 TimeFormatter: function (value, rec, index) { if (value == undefined) { return ""; } /*json格式时间转js时间格式*/ value = value.substr(1, value.length - 2); var obj = eval('(' + "{Date: new " + value + "}" + ')'); var dateValue = obj["Date"]; if (dateValue.getFullYear() < 1900) { return ""; } var val = dateValue.pattern("yyyy-MM-dd HH:mm"); return val; }, DateTimeFormatter: function (value, rec, index) { if (value == null || value == '') { return ''; } var dt; if (value instanceof Date) { dt = value; } else { dt = new Date(value); if (isNaN(dt)) { value = value.replace(//Date((-?d+))//, '$1'); //标红的这段是关键代码,将那个长字符串的日期值转换成正常的JS日期格式 dt = new Date(); dt.setTime(value); } } return dt.pattern("yyyy-MM-dd HH:mm"); }, //EasyUI用DataGrid用日期格式化 DateFormatter: function (value, rec, index) { if (value == undefined) { return ""; } /*json格式时间转js时间格式*/ value = value.substr(1, value.length - 2); var obj = eval('(' + "{Date: new " + value + "}" + ')'); var dateValue = obj["Date"]; if (dateValue.getFullYear() < 1900) { return ""; } return dateValue.pattern("yyyy-MM-dd"); } };
Date.prototype.pattern = function (fmt) { var o = { "M+": this.getMonth() + 1, //月份 "d+": this.getDate(), //日 "h+": this.getHours() % 12 == 0 ? 12 : this.getHours() % 12, //小时 "H+": this.getHours(), //小时 "m+": this.getMinutes(), //分 "s+": this.getSeconds(), //秒 "q+": Math.floor((this.getMonth() + 3) / 3), //季度 "S": this.getMilliseconds() //毫秒 }; var week = { "0": "/u65e5", "1": "/u4e00", "2": "/u4e8c", "3": "/u4e09", "4": "/u56db", "5": "/u4e94", "6": "/u516d" }; if (/(y+)/.test(fmt)) { fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length)); } if (/(E+)/.test(fmt)) { fmt = fmt.replace(RegExp.$1, ((RegExp.$1.length > 1) ? (RegExp.$1.length > 2 ? "/u661f/u671f" : "/u5468") : "") + week[this.getDay() + ""]); } for (var k in o) { if (new RegExp("(" + k + ")").test(fmt)) { fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length))); } } return fmt; }