记录问题:mysql中datetime类型字段在后台读取与前端展示

1.数据库字段类型为datetime,model里:
@Column(name = "createtime", length = 20)
private Date createTime;

2.两种将数据传到前端的方法

方法一:

List<Map<String, Object>> list=targetService.findAll();//这里获取到目标list,省略业务方法
List<Map<String, Object>> newList = new ArrayList<Map<String, Object>>();
for (Map<String, Object> li : list) {
    //String s = li.get("createtime").toString();//覆盖Date对象为字符串
    //li.put("createtime", s);
    newList.add(task);
}
response.setHeader("Content-type", "text/html;charset=UTF-8");
response.setCharacterEncoding("UTF-8");
response.getWriter().print(JSONArray.fromObject(newList).toString());//数据发往前端

前端用$.post请求获得数据:

$.post("/url",{key1:value1,key2:value2},function(res){
    console.log(res);//这里获取到的日期是createtime:{"date":3,"hours":11,"seconds":4,"month":4,"nanos":0,"timezoneOffset":-480,"year":118,"minutes":6,"time":1525316764000,"day":4}
};

在不是异步获取的情况下使用thymeleaf模板引擎渲染数据:

<td th:text="${#dates.format(listist.createtime, 'yyyy-MM-dd  HH:mm:ss')}">创建时间</td>//正确显示时间为2018-05-03 15:01:10

而通过$.post请求获取的话,由于得到日期的是一个对象(如注释),显示为[object,object],需要重新format为指定的格式2018-05-03 15:01:10。原因是:JSONArray.fromObject会把datetime对象转换为json字符串。

尝试:

将Map<String, Object>中的createtime覆盖为字符串,即方法一注释部分。将Date类型属性转换成字符串,为2018-05-03 15:01:10.0多了“.0”,原因是从数据库查询的datetime时间精确到毫秒。

方法二:

类似方法一,用$.ajax请求得到的却是一个时间戳:1525330869000。。。Why?

3.总结:

只有在异步获取数据库datetime类型数据并渲染到页面的时候会有这种问题,获取到createtime:{"date":3,"hours":11,"seconds":4,"month":4,"nanos":0,"timezoneOffset":-480,"year":118,"minutes":6,"time":1525316764000,"day":4}或者时间戳,可以在前端js处理成要展示的格式,也可以像上面写的直接后台覆盖该对象在map中的键值对。

以上是初次遇到该问题,后续再遇到补充。

猜你喜欢

转载自blog.csdn.net/qq_22656233/article/details/80182094
今日推荐