我的 SQL 数据库中有一个日期时间字段,当我尝试在我的 JSP 页面中显示它并使用“dd-MM-yyyy hh:mm:ss”对其进行格式化时,它仅正确显示日期部分。例如,对于存储在数据库中的日期“2012-01-19 12:13:48”,它显示“19-01-2012 12:00:00”。可能是什么问题?
代码:
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss");
sdf.format(rs.getDate("comment_date")); //rs -> ResultSet
最佳答案
来自 java.sql.Date
的 javadoc:
To conform with the definition of SQL DATE, the millisecond values wrapped by a java.sql.Date instance must be 'normalized' by setting the hours, minutes, seconds, and milliseconds to zero in the particular time zone with which the instance is associated.
为了同时保留时间信息,您应该使用 java.sql.Timestamp
。换句话说,将 rs.getDate()
更改为 rs.getTimestamp()
。
关于java - SimpleDateFormat 没有显示正确的日期格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8951911/