jsp页面上读取MySQL数据库datetime时间显示问题

mysql数据库中时间字段选用了datetime,如果通过java实现在jsp页面上显示时间为"年-月-日  时:分"等格式,那么如下代码就会有不同的结果!

实体类中两个变量:

    private Timestamp createDate;// 创建时间
    private Date modifyDate;// 修改时间

接口实现类中给两个变量赋值:

    detail.setCreateDate(rs.getTimestamp("createDate"));
    detail.setModifyDate(rs.getDate("modifyDate"));

通过servlet调用后代码如下:

    //long time = new Date().getTime();
    //Timestamp timestamp = new Timestamp(time);
    //comment.setCreateDate(timestamp);
   comment.setCreateDate(new Timestamp(new Date().getTime()));//与上面三行等价
comment.setModifyDate(
new Date());

在jsp页面上

<!-- 引入jstl标签库 -->
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>

<td class="center"><fmt:formatDate value="${d.createDate}" pattern="yyyy-MM-dd hh:mm"/></td>

<td class="center"><fmt:formatDate value="${c.modifyDate}" pattern="yyyy-MM-dd HH:mm:ss"/></td>

那么createDate字段能按格式输出在jsp页面上,而modifyDate只显示年月日(即使设置了格式也没用!)。hh,变成大写HH就是24小时制。月份的mm必须大写,小写的话显示的是分钟数。

因此,如果想要在jsp页面自定义格式输出日期,而且数据库是datetime,那么java实体类中要使用Timestamp作为变量的返回类型,这样就可以实现需求了!

http://blog.sina.com.cn/s/blog_6ac4b8d701016twf.html

原文地址:https://www.cnblogs.com/areyouready/p/7347464.html