关于json时间数据格式转换与修改

发布时间:2018-11-28 17:27:31编辑:丝画阁阅读(899)

使用easyui获取JSON时间数据时间数据时,通常是一长串的数字而不是我们想要的类似2018-11-01的普通时间格式。

此时我们就需要使用到关于JSON时间的格式化,而将时间转化成我们想要的格式。

一般转化格式

之前一直使用的 toLocaleDateString() 但是用着用着发现了bug,不同浏览器对于 toLocaleDateString() 的解析结果不同,所以很容易造成前一天调试好发现显示正常了,等到第二天又会出现时间格式问题。

后面就换了一种方法,发现这个方法确实要比 toLocaleDateString() 更合适。

话不多说,直接上代码吧

{field:'setupdate',title:'时间',width:100,align:'center',formatter:formatterdate,editor:{

type:'datebox',

options:{

required:true,

}

}} //使用的是easyui-datagrid数据网格

function formatterdate(val, row) { //在外部创建一个时间转化函数 在 field 中进行调用

1

var date = new Date(val); return date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate(); }

这样处理过后就能将时间正常的显示出来了。当然这个转化函数也可以直接在写在 field 中,不过为了代码的美观,还是推荐写在外部。

格式化后在进行行内编辑的时候,发现转化后的时间无法在启动修改编辑时,对 datebox 进行赋值,同时这时候 datebox 选定的日期无法传输到后台。

这时候举要使用到JQuery 的$.extend 方法 对 dataGrid 的editors 进行继承扩展

 1 $.extend($.fn.datagrid.defaults.editors, {
 2 datebox : {
 3 init : function(container, options) {
 4 var input = $('').appendTo(container);
 5 input.datebox(options);
 6 return input;
 7 },
 8 destroy : function(target) {
 9 $(target).datebox('destroy');
10 },
11 getValue : function(target) {
12 return $(target).datebox('getValue');//获得旧值
13 },
14 setValue : function(target, value) {
15 console.info(formatterdate(value));
16 $(target).datebox('setValue', formatterdate(value));//设置新值的日期格式
17 },
18 resize : function(target, width) {
19 $(target).datebox('resize', width);
20 }
21 }
22 });

这样处理过后的时间就能够进行一系列的操作了,

关键字