SimpleDateFormat not showing the right date format

狂风中的少年 提交于 2019-12-11 04:18:44

问题


I have a DateTime field in my SQL database holding and when I try to show it in my JSP page and format it using "dd-MM-yyyy hh:mm:ss", it displays correctly only the date part. For example, for the date "2012-01-19 12:13:48" stored in the database it shows "19-01-2012 12:00:00". What may be the problem?

Code:

SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss");
sdf.format(rs.getDate("comment_date")); //rs -> ResultSet

回答1:


From the javadoc for java.sql.Date:

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.

In order to preserve time information as well, you should be using java.sql.Timestamp. In other words, change rs.getDate() to rs.getTimestamp().




回答2:


An interesting date/time library you could have a look at is Joda Time. It solves many issues of the date/time implementations in the standard library.



来源:https://stackoverflow.com/questions/8951911/simpledateformat-not-showing-the-right-date-format

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!