自定义EasyUI的datetimebox控件日期时间的显示格式(转)

时间:2023-03-09 01:49:26
自定义EasyUI的datetimebox控件日期时间的显示格式(转)

工作中遇到的问题,在此记录一下。

需求:前台页面使用了EasyUI框架,在某一个html页面中要求datetimebox显示格式为年月日和小时,如图所示:

自定义EasyUI的datetimebox控件日期时间的显示格式(转)

尝试过两种方法,分别如下:

第一种方法:

datetimebox 依赖 datebox和timespinner两个组件,拥有datebox的formatter格式化日期和时间显示方式的属性;

重写了formatter属性,来改变日期框的显示方式

$.fn.datetimebox.defaults.formatter = function(date){
//显示格式: 2017-05-08 17(只显示年月日和小时)
var year = date.getFullYear();
var month = date.getMonth() + 1;
var day = date.getDate();
var hour = date.getHours();
month = month < 10 ? '0' + month : month;
day = day < 10 ? '0' + day : day;
hour = hour < 10 ? '0' + hour : hour;
return year + "-" + month + "-" + day + " " + hour;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
自定义EasyUI的datetimebox控件日期时间的显示格式(转)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

重写之后,效果可以正常显示出来,前后台交互也没有问题,但是它把当前系统其它页面中的datetimebox的显示方式全部改掉了。这肯定是不行的了。

第二种方法:

给easyui的datetimebox控件添加formatter和parser两个属性,并定义对应的函数方法;

<input name="startTime" id="startTime${rand}" data-options="formatter:formatter,parser:parser" class="easyui-datetimebox" />
  • 1
自定义EasyUI的datetimebox控件日期时间的显示格式(转)
  • 1
        //修改日历框的显示格式
function formatter(date){
var year = date.getFullYear();
var month = date.getMonth() + 1;
var day = date.getDate();
var hour = date.getHours();
month = month < 10 ? '0' + month : month;
day = day < 10 ? '0' + day : day;
hour = hour < 10 ? '0' + hour : hour;
return year + "-" + month + "-" + day + " " + hour;
} function parser(s){
var t = Date.parse(s);
if (!isNaN(t)){
return new Date(t);
} else {
return new Date(s + ":00:00");
}
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
自定义EasyUI的datetimebox控件日期时间的显示格式(转)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20

自定义EasyUI的datetimebox控件日期时间的显示格式(转)

其它页面:

自定义EasyUI的datetimebox控件日期时间的显示格式(转)

此时页面时间格式正常显示,且不会对其它页面产生影响;

但是出现了兼容性的问题,在Chrome中正常,在Firefox中显示如下:

自定义EasyUI的datetimebox控件日期时间的显示格式(转)

通过调试,最终发现是formatter函数中return语句中拼接字符串时,小时前面有多个空格导致的,只保留一个空格就可以正常显示;

客户需求是小时与日期间隔不能太近,因为容易理解错误,要求离远点;

于是在parser函数中使用s = s.replace(/\s+/,' ')对参数进行处理即要。

完善后的parser函数代码如下:

        function parser(s){
s = s.replace(/\s+/,' ');//解决格式字符串中多个空格拼接在Firefox中无法兼容的问题
var t = Date.parse(s);
if (!isNaN(t)){
return new Date(t);
} else {
return new Date(s + ":00:00");
}
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
自定义EasyUI的datetimebox控件日期时间的显示格式(转)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

现在有多个空格将日期与小时隔离开,在Firefox中也可以正常显示了。效果如下图:

自定义EasyUI的datetimebox控件日期时间的显示格式(转)


总结:

第一种重写formatter方法后,它直接重写了easyui的日期时间控件的显示方式,导致所有页面的格式都会按照重写后的格式来显示;

第二种是将需要重写格式的控件引用对应的样式,不会对其它页面相同的控件产生影响;

转自:http://blog.csdn.net/qgfjeahn/article/details/71428056