我们在平时的开发中由于实际的需求,可能会需要不同的时间格式,这个时候我就在时间对应的字段上进行处理等。但实际上这样都复杂化了。
我觉得我们应该统一接口,前端和后端之间就通过时间戳来传递,后端与数据库之间也是时间戳来传递。
后台和数据库之间的传递
//直接new 一个当前时间的Date对象即可,数据库对应的类型为 datetime
dogVaccine.setVaccineTime(new Date());
后台传到前端一个时间戳,如何在前端对它进行处理呢?
1 jsp页面可以通过 fmt标签来转化
jsp页面时间格式化
需要在jsp页面引入
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
接下来使用这个标签就可以啦
<fmt:formatDate value="${createTime}" pattern="yyyy-MM-dd HH:mm:ss"/>
2 利用js来转化
//这是一个工具方法
var Common = function () {
return {
// 初始化各个函数及对象
init: function () {
},
// 时间戳转换成指定日期格式
formatTime: function(time, format) {
var t = new Date(time);
var tf = function(i){return (i < 10 ? '0' : '') + i};
return format.replace(/yyyy|MM|dd|HH|mm|ss/g, function(a){
switch(a){
case 'yyyy':
return tf(t.getFullYear());
break;
case 'MM':
return tf(t.getMonth() + 1);
break;
case 'mm':
return tf(t.getMinutes());
break;
case 'dd':
return tf(t.getDate());
break;
case 'HH':
return tf(t.getHours());
break;
case 'ss':
return tf(t.getSeconds());
break;
}
})
}
};
}();
jQuery(document).ready(function() {
Common.init();
});
使用方法如下
//cellvalue 为后台传来的时间戳(就是后台传来的Date对象)
var time = Common.formatTime(cellvalue,"yyyy-MM-dd HH:mm:ss");